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 −
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); } }
When you will click on the button “Click to Close”, the frame will close.