gpt4 book ai didi

java - 如何确定通过Input/ActionMap绑定(bind)导致AbstractAction被触发的Key?

转载 作者:行者123 更新时间:2023-12-01 06:19:18 25 4
gpt4 key购买 nike

我正在构建一个InputMap 和ActionMap 将键绑定(bind)到方法。许多按键都会执行类似的操作。我在输入映射中为每个绑定(bind)键都有一个条目。我想将多个 InputMap 条目与同一个 ActionMap 条目相关联,并使用 AbstractAction.actionPerformed(ActionEvent event) 方法中的 ActionEvent 参数来确定按下/释放/键入哪个键。我查看了 getID(),测试了 ActionEvent 是否是 KeyEvent(不是)。有没有办法做到这一点,或者我必须进行不同的重构,以便每个唯一的 ActionMap 条目设置一个参数,然后调用我的(参数化)方法?

这是有效的(但很冗长):

    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;
}
}
};

最佳答案

您应该首先尝试这个简单的逻辑。

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 来区分它们。

关于java - 如何确定通过Input/ActionMap绑定(bind)导致AbstractAction被触发的Key?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14188363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com