开发者

Press [X] button to close JFrame won't invoke dispose method

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)?


If you do EXIT_ON_CLOSE there's precious little need to dispose, as all resources are "disposed" anyway when the JVM exits. I'm putting "disposed" in quotes because in this automatic case, the dispose method is apparently not being called.

Be aware that the public methods in Swing are there for you to call, not all are necessarily called by the innards of Swing. For example, there are setSize() and setLocation() and setBounds() methods – do the former 2 call the latter, or the other way around? It's not defined, so you shouldn't assume.

Similarly, if you want to do something when the frame closes, the way to ensure it would be to hook a WindowListener to the frame, and put your closing action in windowClosing().


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().


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


Does it work if you put instead of EXIT_ON_CLOSE JFrame.EXIT_ON_CLOSE?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜