Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key Bindings Fire Multiple Times when Holding Key

Tags:

java

swing

I'm following this guide to get key binding to work in my application. So far, the key bindings fire successfully, when I press a key. What I expect to happen is when I bind one action to a key pressed event and another action to a key released event, it will fire the first action when the key is pressed down and the second action when the key is released. What actually happens when I hold down a key is both actions get called multiple times. What can I do to achieve my desired behavior?

Here's how I'm implementing the 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 down the up key is Pressed UP, a slight pause, and then multiple Pressed UP values. When I release the up key, I get a Released UP message. The entire output looks like this:

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

The really weird thing is if I replace UP with a keyboard letter key, such as P, everything works as I expect it to.

like image 944
LandonSchropp Avatar asked Dec 14 '25 16:12

LandonSchropp


1 Answers

  • use Boolean value inside Swing Action when once times fired events then change Boolean from false to true or vice versa

  • I'm sorry nobody knows how did you implemented KeyBindings, post an SSCCE

like image 106
mKorbel Avatar answered Dec 16 '25 07:12

mKorbel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!