JFrame以及为什么要继续运行 [英] JFrame and why stay running

查看:152
本文介绍了JFrame以及为什么要继续运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我创建一个JFrame然后程序仍然运行直到(即)我用窗口的小退出按钮关闭它?

Why if I create a JFrame then the program still runs until (i.e) I close it with the small "exit button" of the window?

我找了这个答案我失败了。我唯一猜到的是,当我做新的JFrame()时,它就像一个特殊的 new ,它保留了一个参考在EDT中的对象,因此它将始终被引用(即使是匿名的新)并且它不会被垃圾收集器删除。然后,一旦触发了窗口关闭事件,该对象就会被解除引用并被销毁。

I looked for this answer and I failed. The only thing I guessed is that when I do new JFrame() it's like an special new, that keeps a reference of the object in the EDT, so it will always be referenced (even if was an anonymous "new") and it's not going to be deleted by the garbage collector. Then as soon as the event of windows close is triggered, the object is dereferenced and destroyed.

推荐答案

尝试, yourFrame.setCloseOperation(JFrame.EXIT_ON_CLOSE)

它继续运行的原因是所谓的事件派发线程一直在运行后台,只要您运行非守护程序线程,应用程序就不会终止。来自线程的文档:

The reason it keeps running is that the so called event dispatch thread keeps running in the background, and as long as you have non-daemon threads running, the application will not terminate. From the docs of thread:


当Java虚拟机启动时,通常会有一个非守护进程线程(通常调用方法名为main的某个指定类)。 Java虚拟机继续执行线程,直到发生以下任一情况:

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:


  • 已调用类Runtime的退出方法并且安全管理器允许退出操作发生。

  • 所有非守护程序线程的线程都已死亡,无论是通过从run方法调用返回还是抛出超出run的传播的异常方法。

这不是JFrame的创建开启了 GUI线程。当框架变得可见时,该线程就会启动,并且可能需要调度事件。

It's not the creation of the JFrame that kicks off the "gui-thread". This thread is started when the frame becomes visible and it possibly needs to dispatch events.

这篇关于JFrame以及为什么要继续运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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