Reputation: 1000
I read that DISPOSE_ON_CLOSE should be used instead of EXIT_ON_CLOSE here and got confused. Does setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
terminate the application if it has no other active threads/frames?
I landed on another question that had a link to an article that states:
DISPOSE_ON_CLOSE – Automatically hide and dispose the frame. When this is the only frame in the application the VM will also be terminated.
If my assumption that an application does terminate when it uses DISPOSE_ON_CLOSE
as its value for setDefaultCloseOperation()
is correct, why won't the following application terminate when I click the exit button?
Code:
public class Test extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test();
}
});
}
public Test() {
super();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setPreferredSize(new Dimension(250, 250));
pack();
setVisible(true);
}
}
Update:
I am currently running Mac OS Yosemite, and java -version
outputs:
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)
I ran the program on my usual IDE (Eclipse) and on the command line, but both keep the JVM running after I close the JFrame.
Upvotes: 1
Views: 250
Reputation: 1000
The JVM actually terminates. What happens is while the JVM exits immediately when using EXIT_ON_CLOSE
, it takes up to 15 or more seconds to terminate (on my machine) when I use DISPOSE_ON_CLOSE
.
I wrongfully assumed that the JVM would terminate immediately like in the first scenario, but apparently that's not the case. The minimum amount of time I had to wait was 2 seconds, but it normally takes over 5 seconds, which continuously led me to believe that it would not terminate, and I would forcefully terminate the JVM myself every time.
To me this behavior feels like its not normal, but I suppose that it would be completely transparent to a end-user, since the JFrame
closes as soon as the exit button is clicked.
I have no explanation as to why using these values for setDefaultCloseOperation()
is different for the JVM in such a minimal example.
Upvotes: 2