我不明白如何使用这段代码:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
点击窗口上的x按钮来关闭程序。
我不明白如何使用这段代码:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
点击窗口上的x按钮来关闭程序。
您需要这一行代码
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
当你按下 JFrame 窗口的 X 按钮时,默认行为相当于
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
所以几乎所有的情况下,在创建JFrame时你都需要手动添加那行代码。
我目前正在使用WindowConstants
中的常量,例如WindowConstants.EXIT_ON_CLOSE
,而不是直接在JFrame
中声明相同的常量,因为前者更能体现意图。
JFrame.DISPOSE_ON_CLOSE
。 - Andrew ThompsonWindowConstants
接口已经被引入来替换在JFrame中直接声明的常量,因为它更好地反映了意图。 - Jaime HablutzelJFrame.DISPOSE_ON_CLOSE
。该行为与设置 JFrame.EXIT_ON_CLOSE
时不同。 - Andrew ThompsonsetDefaultCloseOperation(EXIT_ON_CLOSE)
会使应用程序在接收到操作系统发来的关闭窗口事件时退出。当您按下窗口上的关闭(X)按钮时,操作系统会生成一个关闭窗口事件并发送给Java应用程序。该关闭窗口事件将由Java应用程序中的AWT事件循环处理,以响应事件退出应用程序。我花了相当多的时间在互联网上寻找一个优雅的解决方案。通常情况下,我发现有很多相互矛盾的信息。
最终,我得到了以下解决方案:
EXIT_ON_CLOSE
as this can leave resources behind;Do use something like the following in the JFrame initialization:
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
The real discovery was how to actually dispatch a window message to the JFrame. As an example, as part of your JMenuItem for exiting the application, use the following, where the function getFrame()
returns a reference to the 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 is a subclass of Window so may be cast to Window for this purpose.
And, have the following in your JFrame class to handle Window messages:
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.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
JFrame
并在变量中使用JFrame
本身,则可以使用:frame.dispose();
System.exit(0);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
对我来说这个在类扩展帧的情况下有效
System.exit(home.EXIT_ON_CLOSE);