Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFrame.dispose() vs System.exit()

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?

like image 372
Adil Avatar asked Nov 13 '12 12:11

Adil


People also ask

What is Dispose on close in Java?

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.

How do I exit a JFrame program?

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.

What Dispose method?

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.

How do I close a JFrame exit?

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.


1 Answers

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().

like image 114
wattostudios Avatar answered Oct 15 '22 02:10

wattostudios