如何以编程方式关闭JFrame [英] How to programmatically close a JFrame
问题描述
关闭 JFrame
的正确方法是什么,就像用户点击 X
一样关闭按钮,或按 Alt + F4 (在Windows上)?
What's the correct way to get a JFrame
to close, the same as if the user had hit the X
close button, or pressed Alt+F4 (on Windows)?
我有我的默认关闭操作设置我想要的方式,通过:
I have my default close operation set the way I want, via:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
它完全符合我对上述控件的要求。这个问题与此无关。
It does exactly what I want with the aforementioned controls. This question isn't about that.
我真正想做的是使GUI的行为与按 X的行为相同
关闭按钮会导致它出现。
What I really want to do is cause the GUI to behave in the same way as a press of X
close button would cause it to behave.
假设我要扩展 WindowAdaptor
并且然后通过 addWindowListener()
添加我的适配器实例作为监听器。我希望通过 windowDeactivated()
, windowClosing()
和<$ c $看到相同的调用序列c> windowClosed()与 X
关闭按钮一样。可以这么说,撕掉窗户就像告诉它撕裂自己一样。
Suppose I were to extend WindowAdaptor
and then add an instance of my adaptor as a listener via addWindowListener()
. I would like to see the same sequence of calls through windowDeactivated()
, windowClosing()
, and windowClosed()
as would occur with the X
close button. Not so much tearing up the window as telling it to tear itself up, so to speak.
推荐答案
如果你想要GUI来表现就好像你点击了 X
关闭按钮,然后你需要将一个窗口关闭事件发送到窗口
。来自的 ExitAction
关闭应用程序允许您将此功能添加到菜单项或任何轻松使用操作
的组件。
If you want the GUI to behave as if you clicked the X
close button then you need to dispatch a window closing event to the Window
. The ExitAction
from Closing An Application allows you to add this functionality to a menu item or any component that uses Action
s easily.
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
这篇关于如何以编程方式关闭JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!