- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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.
- Related Articles
- How to disable close button on a JFrame in Java?
- How to set default button for JFrame in Java?
- How can we disable the maximize button of a JFrame in Java?
- How to set the location of a button anywhere in JFrame?
- How to hide a div in JavaScript on button click?
- JavaScript Sum function on the click of a button
- How to start new Activity on click button in Android?
- How to remove li elements on button click in JavaScript?
- How to trigger a button click on keyboard "enter" with JavaScript?
- How to enable the “disabled” attribute using jQuery on button click?
- How to click on a button with Javascript executor in Selenium with python?
- How to click on sign up button using Java in Selenium I am able to open page but not able to click?
- Multi-selection of Checkboxes on button click in jQuery?
- Java Program to draw a line on a JFrame in Java
- How to detect click on HTML button through javascript in Android WebView?

Advertisements