views:

27

answers:

2

I have a custom Swing component called NavigationLink which extends JLabel and implements a key event listener like so:

addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        boolean actionInvoked = e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_SPACE;
        if (actionInvoked && NavigationLink.this.clickAction != null) {
            NavigationLink.this.clickAction.run();
        }
    }
});

clickAction is a Runnable which opens a JOptionPane.showMessageDialog which contains a single button, "OK". All of this works fine, the problem is as follows:

  1. User navigates to the NavigationLink using using TAB until is comes into focus
  2. Use pressing ENTER, opening the dialog message, with the 'OK' button in focus by default
  3. User presses ENTER which closes the dialog, but also causes the keyReleased event in our NavigationLink to fire, immediately opening the dialog again!

How can I cancel the ENTER event after it's been handled but the dialog 'OK' button?

A: 

You could try checking the source of the KeyEvent in the keyReleased method by calling getSource(). If the source is not the NavigationLink component then do not call NavigationLink.this.clickAction.run().

jwaddell
Unfortunately, getSource() always returns NavigationLink.this
Stephen Swensen
+1  A: 

DONT use KeyListeners.

You should be using Key Bindings to bind the Enter key to an Action.

camickr
Thanks! I don't know why KeyListeners have this issue and Key Bindings don't, but using Key Bindings did the trick...
Stephen Swensen