Prevent Enter Event from Bubbling to to Main Window
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开发者_Go百科 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?
DONT use KeyListeners.
You should be using Key Bindings to bind the Enter key to an Action.
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().
精彩评论