I have a frame, and want to prompt when the user closes it to save the document. But if they cancel, the frame shouldn\'t close.
frame.addWindowListener(new
Thanks to the input from Thirler and camickr. This is my solution, which I'm sure that some will hate, but avoids duplicating logic in JFrame, and allows client code to setDefaultCloseOperation as usual.
class MyFrame {
@Override protected void processWindowEvent(WindowEvent e) {
try {
super.processWindowEvent(e);
} catch (SaveOnCloseWindowListener.VetoException x) {}
}
}
public class SaveOnCloseWindowListener extends WindowAdapter {
public static class VetoException extends RuntimeException {
}
private final DocumentController documentController;
public SaveOnCloseWindowListener(DocumentController documentController) {
this.documentController = documentController;
}
public void windowClosing(WindowEvent e) {
if (!documentController.onClose())
throw new VetoException();
}
}