java swing 关闭程序,如何从代码中关闭Java Swing应用程序

在Swing应用程序中,正确关闭应用需要确保所有窗口已关闭且无非守护线程运行。设置JFrame的默认关闭操作为'DISPOSE_ON_CLOSE',并检查是否存在未关闭的窗口或非守护线程,如Timer。如果仍有活动窗口或非守护线程,应用将无法正常终止。解决方案包括确保Timer和自定义线程设置为守护线程,或者在适当时候手动停止它们。
摘要由CSDN通过智能技术生成

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

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?

解决方案

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).

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).

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值