Java Swing GUI

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
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *