Reputation: 1511
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% ?
Upvotes: 1
Views: 1087
Reputation: 127
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.
Upvotes: 1
Reputation: 109815
may be would be better look at KeyBindings, that's easily to build Listener
for key actions as KeyListener
Upvotes: 1