开发者

Why doesn't a simple Swing application terminate when a window is shown?

Here's some sample code:

开发者_如何学运维import javax.swing.*;

public class MyApplicatin {
    public static void main(String args[]) {
        JFrame window = new JFrame();
        window.setSize(100,100);
        window.setVisible(true);

        System.out.println("Should terminate after printing this.");
    }
}

Why doesn't this small application terminate after printing the last line?

My guess is that Swing starts a new non-daemon thread. I'm reading about having to do the GUI stuff in Java in a separate thread all the time, if Swing already uses a separate thread, why would anybody write about that?


Why should it? Normally, when you show a Window you'll want control over when the JVM exits. And nothing in the JVM spec says that the JVM must exit when the main() method reaches the end.

Oracle has some documentation on this specific issue:

The reason is that AWT encapsulates asynchronous event dispatch machinery to process events AWT or Swing components can fire. The exact behavior of this machinery is implementation-dependent. In particular, it can start non-daemon helper threads for its internal purposes. In fact, these are the threads that prevent the example above from exiting.

One (of three) restricton on this machinery is this:

There is at least one alive non-daemon thread while there is at least one displayable AWT or Swing component within the application (see Component.isDisplayable).

This means that the JVM will not quit on its own as long as there's a displayable AWT/Swing component around.

Warning: disposing all displayable components does not necessarily mean that the non-daemon thread is gone:

It depends on the implementation if and when the non-daemon helper threads are terminated once all components are made undisplayable.


You'll have to add

window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.dispatchEvent(new WindowEvent(window, Event.WINDOW_DESTROY));

As Joachim said, disposing the window may do the trick too, but it depends on the implementation. In any case, you have to close the window, otherwise the application will keep on running.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜