【问题标题】:What is wrong with this keybinding?这个键绑定有什么问题?
【发布时间】:2013-02-27 03:45:33
【问题描述】:
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应该向右走

【问题讨论】:

  • 您确定是键绑定而不是setVX 方法吗?为每个actionPerformed 方法添加一个调试语句,查看按下D 是否实际上调用setVX(通过actionPerformed 方法)
  • 是的,我的 setVX 是正确的,但是当我摆脱我的 setVY 操作时
  • 我的 VX 工作.. 我不知道为什么当我摆脱我执行的 VY 时它会工作
  • 尝试将调试语句添加到每个actionPerformed 方法中,并查看调用的内容和顺序。我认为这可能与您的stop 操作有关
  • 我不知道 actionperform 有什么问题。也许它只接受两个 actionperform 而不是 3

标签: java swing action key-bindings keystrokes


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多