
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- How to disable close button on a JFrame in Java?
- JavaScript Sum function on the click of a button
- 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 set default button for JFrame in Java?
- How to hide a div in JavaScript on button click?
- How to add Visible On click Button in HTML Code ?
- How to start new Activity on click button in Android?
- How to remove li elements on button click in JavaScript?
- Multi-selection of Checkboxes on button click in jQuery?
- Java Program to draw a line on a JFrame in Java
- Add a pressed effect on button click with CSS
- Unselecting multiple Checkboxes on button click in jQuery?
- How to click on a button with Javascript executor in Selenium with python?
- How to click button Selenium Python?
Advertisements