Search code examples
javaswingactionkey-bindingskeystrokes

What is wrong with this keybinding?


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

 }

Why is that when I press W or D it goes up...

What is the problem?

D should go right


Solution

  • You are overwriting the value in your action map because you are using the same action name "pressed" for both the up and right action.

    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
    

    The following should fix it:

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