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:
- User navigates to the NavigationLink using using TAB until is comes into focus
- Use pressing ENTER, opening the dialog message, with the 'OK' button in focus by default
- 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?