title: How can a Swing WindowListener veto JFrame closing
body: <p>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.</p>
  
  <pre><code>frame.addWindowListener(new SaveOnCloseWindowListener(fileState));
  ...
  public class SaveOnCloseWindowListener extends WindowAdapter {
      private final FileState fileState;
  
      public SaveOnCloseWindowListener(FileState fileState) {
          this.fileState = fileState;
      }
  
      public void windowClosing(WindowEvent e) {
          if (!fileState.onQuit())
              cancelClose();  
      }
  }
  </code></pre>
  
  <p>FileState looks at whether the document is dirty. If it isn't it does nothing and returns true. If it is dirty, it asks the user if he wants to save (YES/NO/CANCEL). If the user cancels at this point, it should abort the windowClosing.</p>
  
  <p>All the suggestions I've seen on the net involve explicitly exiting in the windowClosing method, thus overriding the use of JFrame.setDefaultCloseOperation(), and duplicating the code in JFrame.processWindowEvent(). </p>
  
  <p>I actually have a dirty solution, but would like to see if there are any cleaner ones.</p>
  
  <p>Cheers</p>