Remove key listener from panel

MTHeadss picture MTHeadss · Apr 6, 2012 · Viewed 8.7k times · Source

Is it possible to clear a listener that I put on my JPanel? When I call a method, I put a KeyListener on the panel but when I quit this method, I want to clear that listener.

Here is my method :

private void stopBall(final Graphics2D g2, int posBallY, String winner) {

        move = false;
        scorePanel.showPressSpace(true);    

        setFocusable(true);
        requestFocus();

        addKeyListener(new KeyAdapter() {

            public void keyPressed(KeyEvent e){  
                if (e.getKeyCode() == KeyEvent.VK_SPACE){ 

                    setPosX(getPlayPanelWidth()/2);
                    setPosY(0);

                    move = true;
                    scorePanel.showPressSpace(false);
                    initBall(g2);
                } 

            }});

        if (winner == "player1") {
            scoreCountPlayer1++;
            scorePanel.getLab_Player1().setText("" + scoreCountPlayer1);


        } else if (winner == "comp") {
            scoreCountComputer++;
            scorePanel.getLab_Computer().setText("" + scoreCountComputer);
        }   
    }

Answer

Eric Grunzke picture Eric Grunzke · Apr 6, 2012

You have an unqualified call to addKeyListener(KeyListener), so I presume that you've extended JPanel. If so, then you can call removeKeyListener(KeyListener). In your current code, your key listener is anonymous. You'll need to change it just a bit to hold on to that reference, like so:

// Create a variable holding the listener
KeyAdapter keyAdapter = new KeyAdapter()
{
  public void keyPressed(KeyEvent e)
  {
    if (e.getKeyCode() == KeyEvent.VK_SPACE)
    {
      setPosX(getPlayPanelWidth() / 2);
      setPosY(0);

      move = true;
      scorePanel.showPressSpace(false);
      initBall(g2);
    }

  }
};
// Register the listener with this JPanel
addKeyListener(keyAdapter);

// Time passes...

// Remove the listener from this JPanel
removeKeyListener(keyAdapter);