Is there any way to Close the JFrame without exiting the whole application using Cancel jButton?

user1809580 picture user1809580 · Nov 8, 2012 · Viewed 9k times · Source

is there any way to close the frame using Cancel button without exiting the whole application. I tried Following

setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);

above line works only in case when i press X close button to close the frame. Is there any other good way to implement a JButton to perform the same operation

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class CloseTestForm extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CloseTestForm frame = new CloseTestForm();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public CloseTestForm() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnSave = new JButton("Save");
        btnSave.setBounds(64, 141, 89, 23);
        contentPane.add(btnSave);

        JButton btnCancel = new JButton("Cancel");
        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                //??
            }
        });
        btnCancel.setBounds(64, 192, 89, 23);
        contentPane.add(btnCancel);
    }
}

Answer

Dan D. picture Dan D. · Nov 8, 2012

Use anything for setDefaultCloseOperation excepting EXIT_ON_CLOSE.

Then, for the cancel button, just dispose() the window. If the application has another running thread, it won't exit. You can also hide a window by calling setVisible(false).