1

For a game, I use a KeyListener to know when a key is pressed down.

public synchronized void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
        keyRightIsDown = true;
    }
}

public synchronized void keyReleased(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
        keyRightIsDown = false;
    }
}

This works 99.9%. But from time to time (often enough), the keyReleased is not called, when the key is released (causing the game character to continue moving right - pressing the key again fixes the problem).

[Maybe relevant:] I use OSX 10.6 and I press down multiple keys at the same time quiet often.

How can I make this work 100% ?

Julius Eckert
  • 1,481
  • 4
  • 16
  • 24
  • 2
    I suspect out-of-order events (i.e you get the release before the press for quick keystrokes). Can you count the number of events and see if you get the same number of releases as presses? – Alexander Torstling Jul 18 '11 at 10:54
  • @Alexander: I will try to find out. How would I fix that? – Julius Eckert Jul 18 '11 at 11:24
  • Keep a counter for each key, increment when you get a press event and decrement when you get a release. Consider key down when count <> 0 or >0, depending on how you want the code to behave (treat out-of-order as in-order, or ignore out-of-order). You could also filter out quick presses, if you don't care about them. – Alexander Torstling Jul 18 '11 at 12:14

2 Answers2

1

may be would be better look at KeyBindings, that's easily to build Listener for key actions as KeyListener

mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

similar questions were asked several times, take a look at

how-to-know-when-a-user-has-really-released-a-key-in-java

or

how-to-stop-repeated-keypressed-keyreleased-events-in-swing

i hope this helps;

edit:

what you could do, is using a polling mechanism:

static Toolkit kit = Toolkit.getDefaultToolkit();
..
if (kit.getLockingKeyState(KeyEvent.VK_X))
..

this means you always check in your thread if a certain key is pressed. But keep in mind that polling is not efficient.

Community
  • 1
  • 1
dilbert
  • 127
  • 1
  • 8