Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove key listener from panel

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);
        }   
    }
like image 785
MTHeadss Avatar asked Apr 06 '12 17:04

MTHeadss


People also ask

How do I disable KeyListener?

You can set up a Timer for one second, and when you need to stop receiving key events, just disable the component by setEnabled(false) , then start the timer, and when it runs out, you call setEnabled(true) .

How many methods are there in key listener?

The KeyListener interface is found in java. awt. event package, and it has three methods.


1 Answers

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);
like image 100
Eric Grunzke Avatar answered Oct 12 '22 13:10

Eric Grunzke