问题
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());
回答1:
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.
来源:https://stackoverflow.com/questions/20584539/detect-a-key-being-held-down-in-java-7