当用户在 JDialog 外部单击时如何关闭模态 JDialog?
我有一个未装饰的模态 JDialog,当用户在模态对话框外部单击时,我想将其 setVisible(false) 。
这在 Swing 中可能吗?
我正在做的是弹出一个文本字段的自定义编辑器,例如日期选择器。有没有更简单的方法来做我想做的事?
编辑
请记住,模式会阻止对 setVisible(true) 的调用,因此您不能只是说“不要使用模式对话框”
而且我尝试过将侦听器聚焦在对话框上,但它们不这样做当其模态时不触发。
I have a Undecorated Modal JDialog which I want to setVisible(false) when the user clicks outside of the modal dialog.
Is this possible in Swing?
What I am doing is popping up a custom editor for a text field like a date selector. Is there an easier way to do what I want?
EDIT
Remember that modal blocks on the call to setVisible(true), so you can't just say "don't use a modal dialog"
And I've tried focus listeners on the dialog, they don't trigger when its modal.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
编辑: 更改为使用 WindowFocusListener 而不是 FocusListener,并检查失去焦点的降序组件,以便在子组件获得焦点时不隐藏。
一种简单的方法是在对话框上添加一个窗口焦点侦听器,当焦点丢失时将其隐藏。我认为在这种情况下不需要模态。例如:
EDIT: Changed to use WindowFocusListener instead of FocusListener, as well as check for descending components on the focus lost in order to not hide if a child component gains focus.
A simple way would be to add a window focus listener on the dialog that hides it when focus is lost. I don't see the need for modality in this case. For example:
如果您可以在对话框外部单击并发生“某些事情”,那么它就不是模式对话框。所有答案都是正确的,您应该创建一个非模式对话框,然后通过 FocusListener 处理您的用例。
It's not a modal dialog if you can click outside of it and "something" happens. All the answers are correct, you should be creating a non-modal dialog and then deal with your use case via a FocusListener.
它不一定是模式对话框(模式意味着它会阻止您使用所有者窗口,直到您隐藏该对话框)。最好尝试一下这个:
It's not necessary to be a modal dialog (modal means that it prevents you from using the owner window until you hide the dialog). Better try this:
尝试将模式设置为 false,然后使用 windowsDeactivated() 关闭对话框(dialog.dispose()),对我有用。
Try to set the modal to false, and then use windowsDeactivated() for close de dialog (dialog.dispose()), works for me.
使用 WindowListener 并处理 windowDeactivated() 事件。
Use a WindowListener and handle the windowDeactivated() event.
并不是真正的模态对话框,如果单击其他位置关闭它,也许您需要
setAlwaysOnTop
但是,类似下面的内容应该可以解决问题(未经测试)。请注意,我建议将代码移动到比提供的使用更好的设计中。
Not really a modal dialog then if clicking else where closes it, maybe you want
setAlwaysOnTop
However, something like the following should do the trick (untested). Note, I would recommend moving the code into something better designed than use as provided.
可能添加一个 FocusListener 并隐藏对话框失去焦点。如果对话框中的某些元素可以获得焦点,则可能会很棘手。无论如何,尝试一下。
Probably add a FocusListener and hide the dialog when it looses the focus. May be tricky if some elements in the dialog can have focus. Anyways, experiment with it.