Confirm program quit when cmd + Q is pressed

524 views Asked by At

I have a program with a JFrame that I use a WindowListener to close the program with. I use the following method to prompt a message about saving changes made in the program:

    public void windowClosing(WindowEvent e) {
        if (condition) {
            System.exit(0);
        }

However, when I press cmd + Q, my program will quit without me having the option of saving. Is there a smart way to make sure that I can have a condition before I close my program regardless if I close it through the window X or through my keyboard short commands? Or do I need to create a KeyEvent for this?

2

There are 2 answers

0
czdepski On

You need to change the DefaultCloseOperation on JFrame and then dispose() the frame on windowClosing event (or System.exit(0) like you show above). Here is a simple working example:

JFrame f = new JFrame();
f.setPreferredSize(new Dimension(300, 300));
f.pack();
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
   @Override
   public void windowClosing(WindowEvent we) {
      if (condition) {
         f.dispose();
      }
   }
});
f.setVisible(true);

This way all closing operation will use your condition.

0
camickr On

However, when I press cmd + Q,

I believe that is a keystroke you enter from the command line?

If so you might be able to use addShutDownHook(...) method found in the Runtime class.