我正在构建一个InputMap和ActionMap来将键绑定到方法。许多键都会做类似的事情。我在InputMap中为每个绑定键都有一个条目。我想将几个InputMap条目与相同的ActionMap条目相关联,并使用AbstractAction.actionPerformed(ActionEvent事件)方法中的ActionEvent参数来确定按下/释放/键入的键。我查看了getID(),测试了ActionEvent是否是KeyEvent(它不是)。有没有办法做到这一点,或者我必须有不同的重构,以便每个唯一的ActionMap条目设置一个参数,然后调用我的(paramaterized)方法?
这是有效的(但是很冗长):
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0),"myRightHandler");
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0),"myLeftHandler");
getActionMap().put("myRightHandler",new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Typed Right Arrow");
}
});
getActionMap().put("myLefttHandler",new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Typed Left Arrow");
}
});
这是我想做但却找不到的魔法:
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0),"myGenericHandler");
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0),"myGenericHandler");
getActionMap().put("myGenericHandler",new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
// determine what key caused the event...
// evt.getKeyCode() does not work.
int keyCode = performMagic(evt);
switch (keyCode) {
case KeyEvent.VK_RIGHT:
System.out.println("Typed Right Arrow");
break;
case KeyEvent.VK_LEFT:
System.out.println("Typed Left Arrow");
break;
default:
System.out.println("Typed unknown key");
break;
}
}
};
答案 0 :(得分:-1)
您应该首先尝试这种简单的逻辑。
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0),"myRightHandler");
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0),"myLeftHandler");
getActionMap().put("myRightHandler", new myAction("myRightHandler"));
getActionMap().put("myLeftHandler", new myAction("myLeftHandler"));
class myAction extends AbstractAction {
String str;
public myAction(String actName) {
str = actName;
}
public void actionPerformed(ActionEvent ae) {
switch(str) {
case "myRightHandler": //Here is code for 'myRightHandler'.
break;
case "myLeftHandler": //Here is code for 'myLeftHandler'.
break;
.
.
.
.
default : //Here is default Action;
break;
}
}
}
现在,您可以添加许多自定义按键组合和操作,并通过switch进行更改。