Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 360
Martin Rohwedder Avatar asked Dec 28 '22 05:12

Martin Rohwedder


1 Answers

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);
    }
}
like image 153
tester Avatar answered Dec 29 '22 19:12

tester