我正在使用此代码将键盘键绑定到自定义操作,而不使用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);
一切正常,但我注意到当我按住 ie 时按下SPACE,A动作left
不再触发,如果两个按键的事件都被触发,那就太好了。
有没有办法将键绑定与键组合一起使用?