1

I'm having problems figuring out how to get properly notified when keys are pressed. The keyPressed method doesn't seem to be called again for the first key pressed when handling multiple keys.

Example: if I press the right arrow key and hold onto it, it gets called repeatedly (keeps printing test). But if I press the right arrow key, then press space key once, while holding onto the right arrow key, as soon as the space key is released, the keyPressed() method doesn't seem to be called. (nothing being printed).

This is what my code looks like:

public void keyPressed(KeyEvent e) {

    System.out.println("test");

    switch (e.getKeyCode()) {

        case KeyEvent.VK_LEFT:
            guy.moveLeft();
            break;

        case KeyEvent.VK_RIGHT:
            guy.moveRight();
            break;

        case KeyEvent.VK_SPACE:
            guy.jump();
            break;
    }
}
joce
  • 9,624
  • 19
  • 56
  • 74
sache
  • 11
  • 1
  • 2

1 Answers1

3

Welcome to the wonderful world of keyboard focus.

Assuming that you've attached a KeyListener to a component...

In order for any component to receive a key event it must be focusable and have keyboard focus. This makes it very flaky when you want to use it for something like games.

Instead, you should take advantage of the key bindings API. Apart from making it easier to code key actions, it allows you to specify under what focus conditions the individual events should be triggered.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thanks, I will take a look at the key bindings then. – sache Feb 21 '13 at 04:05
  • I have made some key bindings but it behaves exactly like before. If multiple keys are pressed, the focus doesn't go back to the previous key that is still being pressed after releasing the recent one. – sache Feb 21 '13 at 05:06
  • Instead of listening to the repeat key event, put a flag in or use timer and monitor for the key release, resetting the flag or stopping the timer. I'd suggest using something like `javax.siwng.Timer` – MadProgrammer Feb 21 '13 at 05:10