Key bindings with multiple keys

匿名 (未验证) 提交于 2019-12-03 09:06:55

问题:

I'm using this code to bind keyboard keys to custom actions without using the KeyListener:

Action left = new AbstractAction() {     @Override     public void actionPerformed(ActionEvent e) {         System.out.println("pressed left key");     } };  Action right = new AbstractAction() {     @Override     public void actionPerformed(ActionEvent e) {         System.out.println("pressed right key");     } };  Action space = new AbstractAction() {     @Override     public void actionPerformed(ActionEvent e) {         System.out.println("pressed space key");     } };  myJPanel.getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "pressedLeft"); myJPanel.getInputMap().put(KeyStroke.getKeyStroke("A"), "pressedLeft"); myJPanel.getActionMap().put("pressedLeft", left);  myJPanel.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "pressedRight"); myJPanel.getInputMap().put(KeyStroke.getKeyStroke("D"), "pressedRight"); myJPanel.getActionMap().put("pressedRight", right);  myJPanel.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "pressedSpace"); myJPanel.getActionMap().put("pressedSpace", space); 

Everything works perfectly, but i noticed that when i press i.e. SPACE while holding A, the left action isn't fired anymore, it would be great if events for both pressed keys are fired.

Is there any way to use key bindings with key combinations?

回答1:

See Motion Using the KeyBoard for a potential solution.

An event is only generated for the last key pressed so you need to manually keep track of any other keys that have been pressed (and keep manually simulate firing the event). This is true whether you use key bindings or a KeyListener.



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