- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements