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.
[st_adsense]
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:
[st_adsense]
Lot Thanks To You. Thanks