I'm trying to make a simple applet game in java. I work with the KeyDown method to move an object Up, Down, Left and Right in a 2D-Matrix. This works perfectly but if I press one of the keys down and don't release it, the object moves one field in the right direction, then freezes for some milli seconds and then keeps moving super fast in the same direction. Is there a way I can press the key as long as I want but the object will move just one element in the Matrix?
2 Answers
I am not exactly sure, which framework you use for displaying your applet and handling your Input, but usually KeyPressed is use for operations, which are performed only once after the actual 'key-down'.
Implement the KeyListener-interface. Just like:
public class MyApplet extends Applet implements KeyListener {
...
public void keyPressed(KeyEvent evt) {
//do stuff
}
...
}
Look here: javakode.com/applets/05-keyboardInput and here: java.applet.Applet oracle-reference

- 348
- 1
- 7
- 24
You could add a down
state to your listener:
on key down, if state is up, change state to down and handle event on key up, if state is down, change state to up ignore other events
this way, only the first keyPressed, which is the reall key down, will trigger your code
EDIT: I wanted to add something about the keyRepeats property I seemed to recall, but instead fould this question. It seems to be highly relevant, if yours is not even a duplicate

- 4,061
- 1
- 36
- 58