Keybind on short press

I am following this tutorial to get the key bindings to work in my application. So far, key bindings fire successfully when I press a key. What I expect is when I bind one action to the key pressed event and another action to the event released by the key, it fires the first action when the key is pressed and the second action when the key is released. What actually happens when I hold down a key are actions being called multiple times. What can I do to achieve the desired behavior?

This is how I implement key bindings:

component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("pressed UP"), "pressedUP");
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released UP"), "releasedUP");

Action pressedUpAction = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        System.out.println("Pressed UP");
    }           
};

Action releasedUpAction = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        System.out.println("Released UP");
    }           
};

component.getActionMap().put("pressedUP", pressedUpAction);
component.getActionMap().put("releasedUP", releasedUpAction);

      

When I run the program, the output I actually get when I hold the up key is Pressed UP

, a little pause and then a few values Pressed UP

. When I release the key up, I receive a message Released UP

. The whole output looks like this:

Pressed UP
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Released UP

      

It's really strange if I replace UP with a key with a keyboard letter, for example P

, everything works as I expect.

+3


source to share


1 answer


  • use the Boolean

    value inside Swing Action when firing events once, then change Boolean

    from false

    to true

    or vice versa

  • Sorry no one knows how you implemented KeyBindings , post the SSCCE



+7


source







All Articles