java - 这个键绑定(bind)有什么问题?

标签 java swing action key-bindings keystrokes

public void buttons(){
     int c = WHEN_IN_FOCUSED_WINDOW;

        Action right = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                player.setVX(2);
            }
        };
        Action stop = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                player.setVX(0);
                player.setVY(0);
            }
        };

        Action up = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                player.setVY(-2);
            }
        };
           getInputMap(c).put(KeyStroke.getKeyStroke("D"), "pressed");
           getActionMap().put("pressed", right);
           getInputMap(c).put(KeyStroke.getKeyStroke("released D"), "released");
           getActionMap().put("released", stop);
           getInputMap(c).put(KeyStroke.getKeyStroke("W"), "pressed");
           getActionMap().put("pressed", up);
           getInputMap(c).put(KeyStroke.getKeyStroke("released W"), "released");
           getActionMap().put("released", stop);

 }

为什么当我按 W 或 D 时它会上升...

问题是什么?

D应该向右走

最佳答案

您正在覆盖操作映射中的值,因为您对向上和向右操作使用相同的操作名称“按下”。

getInputMap(c).put(KeyStroke.getKeyStroke("D"), "pressed");
getActionMap().put("pressed", right);
getInputMap(c).put(KeyStroke.getKeyStroke("released D"), "released");
getActionMap().put("released", stop);
getInputMap(c).put(KeyStroke.getKeyStroke("W"), "pressed");
getActionMap().put("pressed", up); // this overwrites the "pressed" action name above with the up action
getInputMap(c).put(KeyStroke.getKeyStroke("released W"), "released");
getActionMap().put("released", stop); // similarly, this is redundant because you have the same thing above

下面应该修复它:

getInputMap(c).put(KeyStroke.getKeyStroke("D"), "right");
getInputMap(c).put(KeyStroke.getKeyStroke("released D"), "stop");
getInputMap(c).put(KeyStroke.getKeyStroke("W"), "up");
getInputMap(c).put(KeyStroke.getKeyStroke("released W"), "stop");
getActionMap().put("right", right);
getActionMap().put("up", up);
getActionMap().put("stop", stop);

关于java - 这个键绑定(bind)有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15103808/

相关文章:

java - 如何通过引用 Java 中包含数组的 HashMap 来向数组添加值?

java - 使用 Mockito 和 Android 模拟 Drawable

java - 在 JFrame 中传递组件列表的 ActionListener

java - 带分层的可扩展面板

c# - 委托(delegate)给实例方法不能有 null 'this'

testing - grails:如何使用多个操作和多个重定向来测试 Controller ?

html - 单击图像时用于调用操作的_正确_ html 元素是哪个?

ArrayList 中的 Java 对象方法

java - 不同版本的库加载到同一个ClassLoader

java - KeyListener 与按键绑定(bind)