如何从代码中关闭Java Swing应用程序 [英] How to close a Java Swing application from the code

查看:268
本文介绍了如何从代码中关闭Java Swing应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从代码中终止Swing应用程序的正确方法是什么,有什么缺陷?

What is the proper way to terminate a Swing application from the code, and what are the pitfalls?

我试图在计时器后自动关闭我的应用程序火灾。但只是在 JFrame 上调用 dispose()没有做到这一点 - 窗口消失但应用程序没有终止。但是,当使用关闭按钮关闭窗口时,应用程序会终止。我该怎么办?

I'd tried to close my application automatically after a timer fires. But just calling dispose() on the JFrame didn't do the trick - the window vanished but the application did not terminate. However when closing the window with the close button, the application does terminate. What should I do?

推荐答案

您的JFrame默认关闭操作可以设置为 DISPOSE_ON_CLOSE 而不是 EXIT_ON_CLOSE (为什么人们继续使用EXIT_ON_CLOSE超出我的范围)。

Your JFrame default close action can be set to "DISPOSE_ON_CLOSE" instead of EXIT_ON_CLOSE (why people keep using EXIT_ON_CLOSE is beyond me).

如果你有任何未曝光的窗口或非守护程序线程,您的应用程序将不会终止。这应该被视为一个错误(并使用System.exit解决它是一个非常糟糕的主意)。

If you have any undisposed windows or non-daemon threads, your application will not terminate. This should be considered a error (and solving it with System.exit is a very bad idea).

最常见的罪魁祸首是java.util.Timer和一个自定义线程你创造了。两者都应设置为守护进程或必须被明确杀死。

The most common culprits are java.util.Timer and a custom Thread you've created. Both should be set to daemon or must be explicitly killed.

如果要检查所有活动帧,可以使用 Frame.getFrames() 。如果处理掉所有Windows /帧,则使用调试器检查仍在运行的任何非守护程序线程。

If you want to check for all active frames, you can use Frame.getFrames(). If all Windows/Frames are disposed of, then use a debugger to check for any non-daemon threads that are still running.

这篇关于如何从代码中关闭Java Swing应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆