2

I'm trying to key bind the a and d keys to make a character move left and right, but the actions only happen once when you press the keys. How can I modify this code to make it do the event while a or d is being held down?

p.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0),"up");
p.getActionMap().put("up", new UpAction());
p.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "left");
p.getActionMap().put("left", new LeftAction());
p.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "right");
p.getActionMap().put("right", new RightAction());
p.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),"quit");
p.getActionMap().put("quit", new StopAction());
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
skyress3000
  • 59
  • 1
  • 7
  • possible duplicate of [Java-check if control key is being pressed](http://stackoverflow.com/questions/11659801/java-check-if-control-key-is-being-pressed) – djechlin Dec 14 '13 at 15:39

1 Answers1

6

Listen for two separate events, one where the key is pressed down, the other where it is released.

Pressing the key should set a flag, releasing it clear said flag. Then you can check the value of the flag instead of continually trying to pester the keyboard. When you're looking at more than just one key, you'd want to store all of the currently pressed KeyStrokes in a map.

Josiah
  • 1,072
  • 6
  • 15
  • 2
    +1 for storing the currently pressed `KeyStrokes` (not key codes) in a Map. For a complete working example check out the `KeyboardAnaimation.java` example from [Motion Using the Keyboard](http://tips4java.wordpress.com/2013/06/09/motion-using-the-keyboard/). – camickr Dec 14 '13 at 15:53