Java Swing 应用程序的 OnExit 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2467070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
OnExit Event For a Swing Application?
提问by Nathan Campos
I'm developing a simple application to manage the operational part of a business using Swing, but I need that when the application exits, it performs this:
我正在开发一个简单的应用程序来使用 Swing 管理业务的运营部分,但我需要在应用程序退出时执行以下操作:
updateZonas();
db.close();
But how can I do this?
但是我该怎么做呢?
采纳答案by Santhosh Kumar Tekuri
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
updateZonas();
db.close();
}
});
This works for any Java application(Swing/AWT/Console)
这适用于任何 Java 应用程序(Swing/AWT/Console)
回答by lins314159
Add a WindowListener
to your JFrame. Its windowClosing
method would call whatever code you need, then System.exit(0)
(or some other return code).
将 a 添加WindowListener
到您的 JFrame。它的windowClosing
方法将调用您需要的任何代码System.exit(0)
(或其他一些返回代码)。
回答by Enrique
Are you using a JFrame? if so you can try this:
你在使用 JFrame 吗?如果是这样你可以试试这个:
myframe.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(WindowEvent winEvt) {
updateZonas();
db.close();
System.exit(0);
}
});