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.