Search code examples
javaswingnetbeansjframewindowlistener

How can save some Objects, directly after the User has closed the Applications JFrame, but before the Program exits?


Good day!

I'm developping a small Java Application with NetBeans IDE that extends JFrame. I implemented several ways to close the App, for example pressing Ctrl-Q and pressing the X of the JFrame.

But before the actual closing I'd like the program to execute some additional code for me, to save some objects the application needs to reuse the next time it starts up.

What is the best way to change the entire programs closing behavior?

I'm thinking about overriding/replacing the defaultCloseOperation, something like this:

    setDefaultCloseOperation( myOwnCloseOperation );

Thanks for any help!


Solution

    1. setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE )
    2. Add a WindowListener or WindowAdapter - overriding either the windowClosing() or windowClosed() methods (I forget which) to catch the closing event.
    3. Call the save functionality from the window method.
    4. Call setVisible(false) or dispose() (as discussed in the comments) at the end.