text: In this section we will discuss about how to close frame on click on the button.
  This example explains you how a frame can be closed on an action event i.e. a frame should be close when clicked on the button on a frame. In this example we will use the dispose() method to close the frame.
  dispose() : Method of java.awt.Window class which is inherited by the javax.swing.JFrame class. This method releases the resources used by the window and their own children. Resources used by this window will be destroyed and the memory consumed by them is returned to the OS.
  Example
  Here we will give you a simple example which will demonstrate you about how to create a frame in Java and close this frame by clicking on a button . In this example we will create a Java class which implements the ActionListener. In this class we will create a method for creating the GUI. The GUI will contain a JFrame and a JButton on frame. Then we will override the actionPerformed() method and we will use the dispose() method inside this method to close the frame when the button will be clicked.
  Source Code
  CloseFrameExample.java
  import java.awt.*; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class CloseFrameExample implements ActionListener { JButton button; JFrame frame; public void createUI() { frame = new JFrame("Copy Frame Data To File Example"); frame.setLayout(null); frame.setSize(400,300); Container pane =frame.getContentPane(); pane.setLayout(null); Insets insets = pane.getInsets(); Dimension size; JPanel p = new JPanel(); p = new JPanel(); pane.add(p); button = new JButton("Close Frame"); button.addActionListener(this); p.add(button); size = p.getPreferredSize(); p.setBounds(150 + insets.left, 100 + insets.top, size.width, size.height); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }// createUI() closed public void actionPerformed(ActionEvent e) { button = (JButton)e.getSource(); frame.dispose(); System.out.println("Frame Closed."); } public static void main(String args[]) { CloseFrameExample cfe = new CloseFrameExample(); cfe.createUI(); }// main() closed }// class closed
  Output
  When you will compile and execute the above example you will get the output as follows :
  When you will click on the "Close Frame" button then the frame will be closed and a message "Frame Closed" will be displayed on the command prompt as follows :
  If you enjoyed this post then why not add us on Google+? Add us to your Circles
  Liked it! Share this Tutorial
  Ask Questions? Discuss: JFrame Close On Button Click
  Post your Comment