What is the difference between these two methods - System.exit()
and JFrame.dispose()
?
If we want to close a Java Swing application when a button is clicked, which method should I use?
DISPOSE_ON_CLOSE will call dispose() on the frame, which will make it disappear and remove the resources it is using. You cannot bring it back, unlike hiding it.
EXIT_ON_CLOSE (defined in JFrame) : Exit the application using the System exit method. Use this only in applications. might still be useful: You can use setVisible(false) on your JFrame if you want to display the same frame again. Otherwise call dispose() to remove all of the native screen resources.
The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.
Now, we have to exit JFrame on close. One simple way of doing this is clicking the cross button on the top right corner of the frame which closes the frame but the application or code will still be running in the background.
System.exit();
causes the Java VM to terminate completely.
JFrame.dispose();
causes the JFrame
window to be destroyed and cleaned up by the operating system. According to the documentation, this can cause the Java VM to terminate if there are no other Windows available, but this should really just be seen as a side effect rather than the norm.
The one you choose really depends on your situation. If you want to terminate everything in the current Java VM, you should use System.exit()
and everything will be cleaned up. If you only want to destroy the current window, with the side effect that it will close the Java VM if this is the only window, then use JFrame.dispose()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With