Java Swing GUI

How to Close a JFrame in Java by a Button

In this tutorial, we are going to see how to close a JFrame in Java by a button by using the method frame.dispose().

First create a button and a frame:

JFrame frame = new JFrame();
JButton btn = new JButton("Click to close!");

Now close the JFrame when clicking the button with Action Listener:

btn.addActionListener(e -> {
   frame.dispose();
});

The following example shows how to close a JFrame when clicking the button.
 

 

Complete example:
import java.awt.*;
import javax.swing.*;

public class Main 
{
   public static void main(String[] args) 
   {
      JFrame frame = new JFrame();
      JButton btn = new JButton("Click to close!");
      frame.setContentPane(btn);
      btn.addActionListener(e -> {
         frame.dispose();
      });
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setPreferredSize(new Dimension(300, 300));
      frame.pack();
      frame.setVisible(true);
   }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

One thought on “How to Close a JFrame in Java by a Button

  • Lot Thanks To You. Thanks

    Reply

Leave a Reply

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