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

I have a simple java graphical application that tells the user a message like "Are you sure you want to exit?" Before he leaves the program. Although this only works when I use my JButton exit program, but when I use the red cross in the JFrame title bar, it doesn’t matter, I click on the β€œYes” or β€œNo” button in the message dialog box.

For this task, I 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 will still exit, how can I stop this action?

+4
source share
1 answer

It seems to me that you need this line:

 frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 

This means that your frame does not close when you click the red X in the upper right corner. But it also means that you need your own implementation that you have already provided.

EDIT: And it seems to me that your code will not work (I could not test it, so I'm not sure about that). You need a 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); } } 
+9
source

Source: https://habr.com/ru/post/1397312/


All Articles