tags:

views:

216

answers:

4

I have set up a JFrame like this:

public class XFrame extends JFrame {

public XFrame() {
    setSize(100, 100);
}
@Override
public void dispose() {
    super.dispose();
    System.out.println("Dispose get called");
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        public void run() {
            XFrame f = new XFrame();
            f.setTitle("Hello World");
            //f.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            f.setDefaultCloseOperation(EXIT_ON_CLOSE);
            f.setVisible(true);
        }
    });
}
}

What I expect is that when I press the close button [X] then the dispose method will be called. However, it's the situation only when DISPOSE_ON_CLOSE is set as the DefaultCloseOperation (???). Java really surprises me here. How to implement a method that would be called in both case of DefaultCloseOperation value (DISPOSE_ON_CLOSE & EXIT_ON_CLOSE)?

+1  A: 

Have you tried adding a WindowListener with the windowClosing() method implemented? That should tell you when it's either a dispose or an exit.

Edit: Just tried it out - should do the job, depending on whether or not you must do something in dispose() rather than in windowClosing().

Ash
+4  A: 
Carl Smotricz
A: 

The documentation of dispose does not mention that it get called when the system gets down. I think it's still not assured (by the javadoc) that it is called for DISPOSE_ON_EXIT...
Anyway System.exit, used by EXIT_ON_CLOSE, is kind of brutal, it shutdowns the virtual machine and there is hardly any chance to run any method after that (despite some finalization hoocks and methods).

I personaly don't like to use EXIT_ON_CLOSE because of that and because it's function can be inhibited by using an SecurityManager

Carlos Heuberger
A: 

For what its worth here is my take on Closing an Application which also provides some simple design solutions.

camickr