Detect a key being held down in java 7

↘锁芯ラ 提交于 2019-12-22 18:42:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!