How can I terminate resources in a safe way when JFrame is about to close?
- If I put terminate() in the a finally block it runs before windowClosing().
- If I put terminate in windowClosing() it can't be accessed from an inner class.
I am aware that I shouldn't use finalize(), but I don't know from where (and how) should I call my terminate() method.
Is there an "official" way to close a JFrame with windowClosing() and do some tasks (save data, close streams) before the program exits? Where should I put my terminate() method?

public class Test extends JFrame {
    private ObjectOutputStream out = null;
    public Test() {
        try  {
            out = new ObjectOutputStream( new FileOutputStream("data.dat"));
            out.writeObject(null);
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }
// The output stream is open and it is used by different methods . . .

// This method closes the stream. I want to call it when the program is closing
    private void terminate() {
        System.out.println("terminated");
        try {
            if (out != null) {
                out.flush();
                out.close();
            }
        } catch (java.io.IOException e) {   
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Test t = new Test();
        try{
            WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
            // I can't call terminate() from here, because it is an inner class
                    System.exit(0);
                }
            };
            t.addWindowListener(l);
            t.setSize(400,200);
            t.setVisible(true);
        } finally {
            // If I call t.terminate() from here it runs before the program is closed
        }
    }
}

ps. Sorry for my English.

How about moving the code out of the main() method to the constructor?
Or make t final so it can be used in the listener method.

Or make it final so it can be used in the listener method.

public static void main(String[] args) {
        final Test t = new Test();
        WindowListener l = new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                t.terminate();
                System.exit(0);
            }
        };

Thank you NormR1! It works. I am very thankful for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.