How do stop exit program when clicking the red cross in JFrame title bar

Martin Rohwedder picture Martin Rohwedder · Feb 19, 2012 · Viewed 9.2k times · Source

I have a simple java GUI application, which will prompt a user for a message like "Are you sure you want to quit?", before he quits the program. Though this only works when I use my Exit Program JButton, but when I use the red cross in the JFrame title bar, then it doesn't matter if I click either yes or no in the message dialog window.

For this task I have added a new WindowListener to my JFrame, with this code

frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent evt) {
        int Answer = JOptionPane.showConfirmDialog(frame, "You want to quit?", "Quit", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (answer == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }
});

If I click no, the program exits anyway, how can I stop that action?

Answer

tester picture tester · Feb 19, 2012

Seems to me that you need this line:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

This means your frame does not close when you click the red X on the upper right. But that also means that you need your own exiting-implementation which you already provided.

EDIT: And it seems to me that your code won't work (I couldn't test it so I am not sure about that). You need the windowClosing() method.

frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
         int Answer = JOptionPane.showConfirmDialog(frame, "You want to quit?", "Quit", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
         if (answer == JOptionPane.YES_OPTION)
             exit(frame);
    }
}