How can I stop the closing of a Java application
Asked Answered
A

4

3

I have a Java Desktop application and I would like when the user selects Exit to get a pop-up window that asks him if he wants to proceed with closing the application or not. I know how to make the window come up and read the user's response but what I need to know is how I can stop the application from closing (something like System.close().cancel()).

Is that possible?

Annular answered 12/12, 2011 at 1:47 Comment(1)
Possible duplicate of How can a Swing WindowListener veto JFrame closingWelter
E
7

Yes it is possible.

After calling setDefaultCloseOperation(DO_NOTHING_ON_CLOSE), add a WindowListener or WindowAdapter and in the windowClosing(WindowEvent) method, pop a JOptionPane.

int result = JOptionPane.showConfirmDialog(frame, "Exit the application?");
if (result==JOptionPane.OK_OPTION) {
    System.exit(0);     
}
Enfeeble answered 12/12, 2011 at 1:56 Comment(0)
R
1

You can add a window listener. (Note: WindowAdapter is in the java.awt.event package)

myframe.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        // do something
    }
});
Rowena answered 12/12, 2011 at 1:52 Comment(0)
M
1

After setting the setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); to your JFrame or JDialog, add a windows listener :

addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent arg0) {
            int result = JOptionPane.showConfirmDialog((Component) null, "Do u really want to exit ?!",
                    "Confirmation", JOptionPane.YES_NO_OPTION);
            if (result == 0) {
                System.exit(0);
            } else {

            }
        }
    });
Merriment answered 30/12, 2015 at 23:3 Comment(0)
S
0

On your JFrame, you have to set a defaultCloseOperation:

JFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

Then set your pop-up's closing operation to EXIT_ON_CLOSE.

Scharaga answered 12/12, 2011 at 1:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.