按住键时,Java KeyListener.keyPressed多次执行

时间:2015-12-07 03:52:48

标签: java keylistener keyevent keycode

使用keyListeners时,如何使每次用户按下左键时,count的值仅增加1,而不是根据持有的时间长度增加?

public void keyPressed (KeyEvent e){
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_LEFT){
          keyLabel.setText("left");
          count++;}

1 个答案:

答案 0 :(得分:2)

考虑一个KeyListener的例子,它只计算每次按下VK_LEFT一次 - 即使按键被按下并多次触发。

label.addKeyListener(new KeyAdapter() {

       boolean pressed = false;
       @Override
       public void keyPressed (KeyEvent e){
            int keyCode = e.getKeyCode();
            if (keyCode == KeyEvent.VK_LEFT && !pressed){
                pressed = true;
                keyLabel.setText("left");
                System.out.println("Pressed: " + (++count));
            }
       }
       @Override
       public void keyReleased (KeyEvent e){
            int keyCode = e.getKeyCode();
            if (keyCode == KeyEvent.VK_LEFT){
                pressed = false;
                System.out.println("Released.");
            }
       }                
   });

虽然在按下键时似乎重复调用了keyPressed,但只有在释放键时才会触发keyReleased,所以我们在那时切换一个布尔开关pressed