When i create a simple program with a JFrame ,from the moment the setVisible method is true, no matter what i do with the frame, the program doesn't exit.Could someone explain me the flow? Thanks
-
Can you provide a code sample? – Brian White Dec 03 '12 at 20:25
-
1Got [daemon threads](http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.8)? – trashgod Dec 03 '12 at 22:28
4 Answers
When you call myJFrame.setVisible(true)
you are creating a non-daemon Swing event thread which prevents the program from ending until this thread and all non-daemon threads have ended. Note, if you want the program to end when the JFrame is closed, call
myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

- 283,665
- 25
- 256
- 373
When a JFrame is open, I know that the program will continue updating the JFrame even if it is invisible, to do things such as check if it is visible again, and also to check if the screen needs updating. If you want to close the program when a JFrame closes, you can use:
JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
which doesn't update the thread that checks for the visibility, it just stops the program when the JFrame stops being visible.

- 193
- 1
- 8
-
*"it just stops the program.."* If by that, you mean 'kills the VM along with all other running threads', then yes. – Andrew Thompson Dec 04 '12 at 02:01
Maybe you're missing the frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
?
Where frame
is whatever the name of your frame is.

- 3,471
- 2
- 29
- 40
From the docs for setDefaultCloseOperation(int)
.
You must specify one of the following choices:
DO_NOTHING_ON_CLOSE
(defined inWindowConstants
): Don't do anything; require the program to handle the operation in thewindowClosing
method of a registeredWindowListener
object.HIDE_ON_CLOSE
(..): Automatically hide the frame after invoking any registeredWindowListener
objects.DISPOSE_ON_CLOSE
(..): Automatically hide and dispose the frame after invoking any registeredWindowListener
objects.EXIT_ON_CLOSE
(..): Exit the application using the System exit method. Use this only in applications.
My choice to high-light the 3rd, since it is typically better than the last. Here are two reasons why.
- Multiple frame instances can be opened and disposed of sequentially, as in this example.
- The only reason the JVM will not exit on closing the last frame is because there are other non-daemon threads running. This in turn, is a sign they should be shut down properly. In this context, 'killing the virtual machine with
System.exit(n)
' does not constitute 'properly'.

- 1
- 1

- 168,117
- 40
- 217
- 433