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?

elixenide
  • 44,308
  • 16
  • 74
  • 100
user998388
  • 81
  • 2
  • 5
  • Possible duplicate of [How can a Swing WindowListener veto JFrame closing](http://stackoverflow.com/questions/3777146/how-can-a-swing-windowlistener-veto-jframe-closing) – Autar Jan 07 '16 at 10:20

4 Answers4

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);     
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
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 {

            }
        }
    });
MedEzzeri
  • 11
  • 2
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
    }
});
Will
  • 19,661
  • 7
  • 47
  • 48
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.

Jon Egeland
  • 12,470
  • 8
  • 47
  • 62