0

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?

DontDivideByZero
  • 1,171
  • 15
  • 28
Jan
  • 1
  • 1
  • possible duplicate of [How to stop repeated keyPressed() / keyReleased() events in Swing](http://stackoverflow.com/questions/1736828/how-to-stop-repeated-keypressed-keyreleased-events-in-swing) – Silly Freak Jan 16 '15 at 09:07

2 Answers2

0

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

Simon K.
  • 348
  • 1
  • 7
  • 24
0

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

Silly Freak
  • 4,061
  • 1
  • 36
  • 58