3

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

General Grievance
  • 4,555
  • 31
  • 31
  • 45
EscapistGR
  • 51
  • 4

4 Answers4

3

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);
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
3

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.

John Schneider
  • 193
  • 1
  • 8
2

Maybe you're missing the frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)?

Where frame is whatever the name of your frame is.

Nico
  • 3,471
  • 2
  • 29
  • 40
1

From the docs for setDefaultCloseOperation(int).

You must specify one of the following choices:

  • DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.
  • HIDE_ON_CLOSE (..): Automatically hide the frame after invoking any registered WindowListener objects.
  • DISPOSE_ON_CLOSE (..): Automatically hide and dispose the frame after invoking any registered WindowListener 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.

  1. Multiple frame instances can be opened and disposed of sequentially, as in this example.
  2. 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'.
Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433