How to close JFrame on the click of a Button in Java


Set frame.dispose() on the click of a button to close JFrame. At first create a button and frame −

JFrame frame = new JFrame();
JButton button = new JButton("Click to Close!");

Now, close the JFrame on the click of the above button with Action Listener −

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

The following is an example to close JFrame on the click of a Button −

Example

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JButton button = new JButton("Click to Close!");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setContentPane(button);
      button.addActionListener(e -> {
         frame.dispose();
      });
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setPreferredSize(new Dimension(550, 300));
      frame.getContentPane().setBackground(Color.ORANGE);
      frame.pack();
      frame.setVisible(true);
   }
}

Output

When you will click on the button “Click to Close”, the frame will close.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements