JFrame Exit on Close Java Swing
In this tutorial, we are going to see how to exit and close a JFrame in Java Swing. You can easily close your JFrame by clicking on the X(cross) in the upper right corner of the JFrame. However JFrame.setDefaultCloseOperation(int) is a method provided by JFrame class, you can set the operation that will happen when the user clicks the X(cross). If “0” is given as a parameter, JFrame will not close even after clicking the X(cross).
It is recommended to use JFrame.EXIT_ON_CLOSE, it exits the application(JFrame) and frees memory.
- JFrame.HIDE_ON_CLOSE: It does not close JFrame, it just hides it.
- JFrame.DISPOSE_ON_CLOSE: It deletes the frame, but it keeps running and consumes memory.
- JFrame.DO_NOTHING_ON_CLOSE: It does nothing when the user clicks on Close.
Example : JFrame Exit on Close
import javax.swing.JFrame; public class Main { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(300, 300); // Exit the application and free memory frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }