如果基础窗口在 ESC 上关闭,如何为 JPopupMenu 启用 ESC-Close?
想象一下两种常见情况的结合:一个 JDialog(或 JFrame)在 VK_ESCAPE(设置为根窗格上的键绑定)上关闭,而内部 JPopupMenu 也应该在 ESC 上关闭。问题是:如果弹出窗口可见,按 escape 总是会关闭对话框 - 事件。显然,弹出窗口甚至没有接收到按键事件,因此弹出窗口无法使用它。有什么方法可以使其正常工作,以便在第一个 ESC 事件时关闭弹出窗口,在第二个事件时关闭对话框? 顺便说一句:它确实可以与 JComboBox 一起使用,默认情况下,当按下 escape 时 JComboBox 会关闭。
Imagine two common situations combined: A JDialog(or JFrame) which closes on VK_ESCAPE (set as key binding on the root pane) and an inner JPopupMenu which is supposed to close on ESC as well. The problem is: pressing escape always closes the dialog - event if the popup is visible. Apparently the popup doesn't even receive the key event so it can't be consumed by the popup. Is there any way to get this working correctly, so that on the first ESC-event the popup is closed and on the second the dialog closes?
By the way: It does work with a JComboBox, which by default closes when escape is pressed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
找到一个通用的解决方案是一个挑战。我们需要考虑何时:
我确定在这两种情况下,当按下转义键时,根窗格实际上具有焦点。
在第一种情况下,我只是搜索根窗格以查看 JPopupMenu 是否已添加到 GUI。如果是这样,那么我们可以关闭弹出窗口。
在第二种情况下,创建一个窗口来包含 JPopupMenu,因此我进行搜索以查看是否显示可见的自定义弹出窗口。如果是这样,那么我就把窗户处理掉。
如果上述两种情况都不成立,那么您可以直接关闭对话框。
您还需要下载 Swing Utils 类。
Finding a generic solution was a bit of a challenge. We need to consider when:
I determined that in both cases the root pane actually has focus when the escape key is pressed.
In the first case I just search the root pane to see if a JPopupMenu has been added to the GUI. If so, then we can just close the popup.
In the second case a Window is created to contain the JPopupMenu so I do a search to see if a visible custom popup Window is displayed. If so, then I dispose of the window.
If neither of the above two cases is true then you can just close the dialog.
You will also need to download the Swing Utils class.
我也遇到了这个问题。 @camickr 提供的解决方案对我来说似乎不太好。所以我检查了引擎盖下发生了什么。打开弹出窗口时,作为弹出窗口调用者的组件将失去焦点。焦点转到 JDialog 的 JRootPane,然后委托给弹出窗口。因此,我没有在 JRootPane 上注册“ESC”快捷方式,而是将其放在 ContentPane 上。这样,只有当 JRootPane 以外的任何内容获得焦点时,对话框才会在 ESC 上关闭。
I encountered the problem as well. The solution provided by @camickr didn't seem very nice to me. So I checked out what's going on under the hood. When opening a popup, the component that is the invoker of the popup loses focus. The focus goes over to the JRootPane of the JDialog which then delegates to the popup. So instead of registering the "ESC" shortcut on the JRootPane, i simply put it on the ContentPane. This way, the dialog only closes on ESC when anything other than the JRootPane is focused.