tags:

views:

76

answers:

2

Why doesn't this Swing-based program terminate when its window is closed?

import javax.swing.JFrame;
import javax.swing.JOptionPane;

final class App extends JFrame {
    private App() {
        super("App");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JOptionPane.showMessageDialog(this, "App works");
        pack();
    }

    public static void main(final String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new App().setVisible(true);
            }
        });
    }
}
+1  A: 

It does... what happens (on my machine) is that it opens up a dialog box. Once you hit "OK" on that dialog box it open up the JFrame. When you close the JFrame it terminates the app.

Yoy probably don't want to be doing the work you are doing inside of the constructor... then the JFrame will show up before the dialog box.

TofuBeer
It doesn't terminate on my system (see @Thomas comment in Question). The window does disappear, but the process doesn't terminate.
Steve Emmerson
I don't see how the JFrame could "show up" before the dialog box because the box is made a component of the JFrame before the JFrame is made visible.
Steve Emmerson
It shows up before the window because the constructor executes before the setVisible call which makes the frame visible.
TofuBeer
@Steve once you close the JFrame it exits. The dialog box is one of two top level gui components that displays. Only closing the JFrame (not clicking OK on the dialog) terminates the app.
TofuBeer
+3  A: 

It doesn't terminate on anyone's system, first of all.

The reason is because you are calling a JFrame to be set visible with zero contents. It's most likely hiding very very small in the upper left hand corner of your screen. If you close that frame your program will terminate. The message dialog has nothing to do with the JFrame.

Ryan