title: In Java, where to put code to reliably fire on window close?
body: <p>I have several windows that I want to save defaults from, after the time the user takes action to close the window (by the button in the title bar, a menu item or a button I've provided) and before it's disposed of. </p>
  
  <ul>
  <li>Some windows I can DISPOSE_ON_CLOSE but some I need info from before they're disposed().</li>
  <li><a href="http://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowListener.html#windowClosed(java.awt.event.WindowEvent)" rel="nofollow">formWindowClosed</a> seems only to fire when the window is disposed of, which I can't always rely on (see above &amp; below)</li>
  <li><a href="http://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowListener.html#windowClosing(java.awt.event.WindowEvent)" rel="nofollow">formWindowClosing</a> seems to fire only when the user closes the window from the titlebar's system menu, even though I call System.exit(0) in my own menu action handler</li>
  <li>According do GC documentation, the dispose() method is not always called and is frequently ignored on app shutdown.  </li>
  <li>I've <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#addShutdownHook-java.lang.Thread-" rel="nofollow">added a <strong>ShutdownHook</strong></a> to run System.runFinalization() but the code is still not being executed. This may be too late anyways, as some windows will have been disposed of by then.</li>
  </ul>
  
  <p>How can I ensure that the code is run before the window is disposed of?  It is a task that the window should be able to take care of, itself.  I'm kind of frustrated at the unreliability of the Closed, Closing and dispose events.  What am I missing?</p>