问题
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?
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.
回答1:
Try, 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:
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:
- The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
- All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
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.
来源:https://stackoverflow.com/questions/3486279/jframe-and-why-stay-running