从面板中删除键侦听器

时间:2012-04-06 17:13:22

标签: java swing jpanel keylistener

是否可以清除我放在JPanel上的听众?当我调用一个方法时,我在面板上放了KeyListener但是当我退出这个方法时,我想清除那个监听器。

这是我的方法:

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 个答案:

答案 0 :(得分:5)

您对addKeyListener(KeyListener)进行了非限定调用,因此我假设您已经扩展了JPanel。如果是这样,那么你可以调用removeKeyListener(KeyListener)。在您当前的代码中,您的密钥监听器是匿名的。您需要稍微更改它以保持该引用,如下所示:

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

答案 1 :(得分:0)

或者对代码进行绝对最小调整的方式

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

但正如评论中已经说明的那样,您应该选择键绑定而不是键入键