拆下面板按键监听​​器(Remove key listener from panel)

2019-09-16 09:29发布

是否有可能清除侦听我把我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);
        }   
    }

Answer 1:

你必须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);


Answer 2:

或与绝对最低限度的调整你的代码的方式

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

但正如在评论中已经说过,你应该选择键绑定,而不是keylisteners



文章来源: Remove key listener from panel