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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With