如何从代码中关闭 Java Swing 应用程序 [英] How to close a Java Swing application from the code
问题描述
从代码中终止 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/Frames 都被处理掉了,那么使用调试器来检查任何仍在运行的非守护线程.
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屋!