I want to call a method confirmExit()
when the red close button of the title bar of a JFrame is clicked.
How can I capture that event?
I'd also like to prevent the window from closing if the user chooses not to proceed.
You can use super. dispose() method which is more similar to close operation. Show activity on this post. You cat use setVisible () method of JFrame (and set visibility to false ) or dispose () method which is more similar to close operation.
EXIT_ON_CLOSE (defined in JFrame) : Exit the application using the System exit method. Use this only in applications. might still be useful: You can use setVisible(false) on your JFrame if you want to display the same frame again. Otherwise call dispose() to remove all of the native screen resources.
Calling setDefaultCloseOperation(EXIT_ON_CLOSE) does exactly this. It causes the application to exit when the application receives a close window event from the operating system.
import javax.swing.JOptionPane; import javax.swing.JFrame; /*Some piece of code*/ frame.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { if (JOptionPane.showConfirmDialog(frame, "Are you sure you want to close this window?", "Close Window?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){ System.exit(0); } } });
If you also want to prevent the window from closing unless the user chooses 'Yes', you can add:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
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