我不明白如何使用这段代码:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
用x键关闭程序。
你需要一行
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
因为按下X按钮时JFrame的默认行为相当于
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
所以在创建JFrame
时,几乎所有时候都需要手动添加这一行我目前指的是WindowConstants
中的常量,如WindowConstants.EXIT_ON_CLOSE
,而不是直接在JFrame
中声明的相同常量,因为之前的常量更好地反映了意图。
如果没有,JFrame将被丢弃。框架将关闭,但应用程序将继续运行。
调用setDefaultCloseOperation(EXIT_ON_CLOSE)
就是这样做的。当应用程序从操作系统接收到关闭窗口事件时,它会导致应用程序退出。按下窗口上的close (X)按钮会导致操作系统生成一个关闭窗口事件并将其发送给Java应用程序。关闭窗口事件由Java应用程序中的AWT事件循环处理,该事件将退出应用程序以响应该事件。
如果不调用此方法,AWT事件循环可能不会在响应close window事件时退出应用程序,而是让它在后台运行。,
我花了相当多的时间在互联网上寻找一个优雅的解决方案。和往常一样,我发现了很多相互矛盾的信息。
我最后以:
结尾- 不要使用
EXIT_ON_CLOSE
,因为这会留下资源; 一定要在JFrame初始化中使用如下内容:
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
真正的发现是如何实际地将窗口消息分派给JFrame。例如,作为退出应用程序的JMenuItem的一部分,使用以下代码,其中函数
getFrame()
返回对JFrame的引用:public class AppMenuFileExit extends JMenuItem implements ActionListener { // do your normal menu item code here @Override public void actionPerformed(ActionEvent e) { WindowEvent we; we = new WindowEvent((Window) App.getFrame(), WindowEvent.WINDOW_CLOSING); App.getFrame().dispatchEvent(we); } }
JFrame是Window的一个子类,所以可以转换为Window。
并且,在JFrame类中使用以下代码来处理窗口消息:
public class AppFrame extends JFrame implements WindowListener { // Do all the things you need to for the class @Override public void windowOpened(WindowEvent e) {} @Override public void windowClosing(WindowEvent e) {/* can do cleanup here if necessary */} @Override public void windowClosed(WindowEvent e) { dispose(); System.exit(0); } @Override public void windowActivated(WindowEvent e) {} @Override public void windowDeactivated(WindowEvent e) {} @Override public void windowDeiconified(WindowEvent e) {} @Override public void windowIconified(WindowEvent e) {} }
如果你使用的是Frame (class Extends Frame),你将无法获得
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
如果您不扩展JFrame
并在变量中使用JFrame
本身,则可以使用:
frame.dispose();
System.exit(0);
下面的代码为我工作:
System.exit(home.EXIT_ON_CLOSE);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
这在类扩展框架