Remove key listener from panel

2019-06-22 05:43发布

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);
        }   
    }

2条回答
姐就是有狂的资本
2楼-- · 2019-06-22 06:29

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);
查看更多
太酷不给撩
3楼-- · 2019-06-22 06:35

Or the way with the absolute minimal adjustments to your code

addKeyListener(new KeyAdapter() {
  public void keyPressed(KeyEvent e){  
    if (e.getKeyCode() == KeyEvent.VK_SPACE){ 
      ((JPanel)e.getSource()).removeKeyListener( this );
      setPosX(getPlayPanelWidth()/2);
      setPosY(0);

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

But as already stated in the comments, you should opt for keybindings instead of keylisteners

查看更多
登录 后发表回答