tags:

views:

654

answers:

3

If I make a JFrame like this

public static void main(String[] args) {

     new JFrame().setVisible(true);
}

then after closing the window the appication doesn't stop (I need to kill it).

What is the proper way of showing application's main windows ?

I'd also like to know a reason of a proposed solution.

Thanks in advance.

+11  A: 

You should call the setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); on your JFrame.

Example code:

public static void main(String[] args) {
     Runnable guiCreator = new Runnable() {
      public void run() {
       JFrame fenster = new JFrame("Hallo Welt mit Swing");
       fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       fenster.setVisible(true);
      }

     };
     SwingUtilities.invokeLater(guiCreator);
    }
Burkhard
I hate Java sometimes. That should be the default behaviour, in my opinion.
Guido
Ok i found the reason - there are two additional AWT threads running and that's why my application doesn't end when the "main" method ends. I always forget that JFrame is nonmodal and creates those threads.
lbownik
Why should it be the default behavior? Many applications create multiple windows. If that were the default you'd have to change it whenever you create a new window.
Herms
+2  A: 

There's a difference between the application window and the application itself... The window runs in its own thread, and finishing main() will not end the application if other threads are still active. When closing the window you should also make sure to close the application, possibly by calling System.exit(0);

Yuval =8-)

Yuval
+2  A: 

You must dispose the frame, invoking the dispose method in your window listener or using setDefaultCloseOperation. For the argument of the last one, you can use two options: DISPOSE_ON_CLOSE or EXIT_ON_CLOSE.

DISPOSE_ON_CLOSE only dispose the frame resources.

EXIT_ON_CLOSE disposes the frame resources and then invokes System.exit.

There is no real difference between the two unless you have non daemon threads. I prefer to use DISPOSE_ON_CLOSE because this way I'm able to notice if I forgot to terminate a thread, because the JVM will stop if there are no more threads running. That's also the reason closing a Frame without disposing will not terminate the application, since Swing creates a thread to handle events that is terminated only when dispose is invoked.

jassuncao