Search code examples
javaswingkey-bindings

Keybindings don't work Java Swing


I'm working on implementing keybindings on a panel that listen if the arrow keys are pressed or not.

If they are pressed, they do an action. My code:

private void createKeyBindings(){
        actionMap = this.getActionMap();
        inputMap = this.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        this.getInputMap().put(KeyStroke.getKeyStroke("a"),
                "pressedUpArrow");
        this.getInputMap().put(KeyStroke.getKeyStroke("released UP"),
                "releasedUpArrow");
        this.getActionMap().put("pressedUpArrow",
                 new PressedUpArrowAction());
        this.getActionMap().put("releasedUpArrow",
                new ReleasedUpArrowAction());
    }

The actions work (when I map them to a button and press the button, it does what the action is supposed to do).

These keybindings are called for my panel (which is a tab in a tabbedpane). I tried both with keystroke pressed UP and just a (to make sure that is not the issue). I type these keys when the tab in question is in focus.

Any advice?


Solution

  • One possible cause of your problem is this:

    this.getInputMap().put(KeyStroke.getKeyStroke("a"),
                "pressedUpArrow");
    

    Shouldn't it be this?

    this.getInputMap().put(KeyStroke.getKeyStroke("UP"),
                "pressedUpArrow");
    

    The way that you've currently coded it, the PressedUpArrowAction() and ReleasedUpArrowAction() fire on the press of one key and the release of a different key.