防止 Enter 事件冒泡到主窗口
我有一个名为 NavigationLink 的自定义 Swing 组件,它扩展了 JLabel 并实现了一个关键事件侦听器,如下所示:
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 是一个 Runnable,它打开一个 JOptionPane.showMessageDialog,其中包含一个按钮“确定”。所有这些工作正常,问题如下:
- 用户使用 TAB 导航到 NavigationLink,直到成为焦点
- 使用按 ENTER 键,打开对话框消息,默认情况下“确定”按钮处于焦点
- 用户按 ENTER 键关闭对话框,还会导致我们的 NavigationLink 中的 keyReleased 事件触发,立即再次打开对话框!
如何在处理完 ENTER 事件后取消该事件,但取消对话框“确定”按钮?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要使用 KeyListener。
您应该使用 按键绑定 将 Enter 键绑定到行动。
DONT use KeyListeners.
You should be using Key Bindings to bind the Enter key to an Action.
您可以尝试通过调用 getSource() 在 keyReleased 方法中检查 KeyEvent 的来源。如果源不是 NavigationLink 组件,则不要调用 NavigationLink.this.clickAction.run()。
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().