wvdz
wvdz

Reputation: 16651

KeyEventDispatcher invoked twice in Java

In my Swing application, I need to set some global key bindings. I use a KeyEvent Dispatcher for this, like this:

public class MyKeyEventDispatcher implements KeyEventDispatcher
{

    @Override
    public boolean dispatchKeyEvent(KeyEvent e)
    {
        if (!e.isConsumed())
        {
            if (e.getKeyCode() == KeyEvent.VK_F8)
            {
                System.out.println("F8");
                e.consume();
                return true;
            }
        }
        return false;
    }
}

My problem is that this is invoked twice when I hit the F8, once for keyup and once for keydown. How can I detect if it is the keyup or keydown event?

I thought I found the answer here: dispatchKeyEvent() invoking twice, but unfortunately, that only works in Android.

Upvotes: 2

Views: 1866

Answers (1)

wvdz
wvdz

Reputation: 16651

The answer was in the comments from @biziclop: use e.getID() to detect the key event. It was also noted that I should check the modifiers to avoid triggering on Shift+F8, Ctrl+F8 etc.

(e.getKeyCode() == KeyEvent.VK_F8 && e.getID() == KeyEvent.KEY_PRESSED && e.getModifiers() == 0)

Upvotes: 4

Related Questions