happyfacelegion
happyfacelegion

Reputation: 53

Java KeyListener.keyPressed firies multiple times while key is held down

When using keyListeners,how do you make it so that the value of count only increases by one each time the user presses the left key instead of increase based on how long you hold it?

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

Upvotes: 4

Views: 2237

Answers (1)

Jan
Jan

Reputation: 13858

Consider this example of a KeyListener that would count each press of VK_LEFT only once - even if key is held down and firing multiple times.

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

While keyPressed seems to be repeatedly called while key is pressed, keyReleased is only fired once the key is released, so we toggle a boolean switch pressed at that time.

Upvotes: 2

Related Questions