Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing and closing windows in Java

Okay, so this might be a stupid question, but I'm new to Java and trying to teach myself things the right way before I develop any bad habits.

Anyway, I was writing a program last night that consisted of a custom class extending Frame and a custom class extending Canvas. The main() method is in the canvas class and I create an instance of the frame class there. The problem is that when the program detects a window close event, I can't dispose the frame because I seemingly have no way to access it from outside the main method. And if I try to define it outside of main(), then I can't use it within. So I ended up skipping dispose() and just using System.exit(0). Is this alright? Is it basically doing the same thing anyway? Or is this a problem I need to fix, and if so, any idea how?

Thanks so much for reading,

Cody

like image 955
Keysmack Avatar asked Jan 19 '11 15:01

Keysmack


2 Answers

You can get a reference to the frame, from the source property of the event:

class MyWindowListener extends WindowAdapter {

    public void windowClosing(WindowEvent e){
         Frame frame = (Frame) e.getSource();
         frame.dispose();
    }

}

Alternatively, since this is an anonymous class (presumably) declared within the constructor, you also have access to the enclosing instance, so you can also write it as:

class MyFrameClass extends Frame {
    public MyFrameClass() {
        this.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                 MyFrameClass.this.dispose();
            }
        });
    }
}

Or you can make it simpler still (as your WindowListener does not have a method of its own called "dispose"):

public void windowClosing(WindowEvent e){
     dispose();
}
like image 56
finnw Avatar answered Oct 26 '22 09:10

finnw


Not a stupid question. Because of the garbage collector its not such a big issue, however, there are some times when you will want to execute some cleanup when a window closes. So some suggestions:

The Window Closing event should be handled from the Frame itself. For instance:

    this.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e){
                  //code here to perform as the window is about to close.
         }
        });

And I would suggest that you create a separate class for your main method that will invoke the Frame etc.

like image 38
Vincent Ramdhanie Avatar answered Oct 26 '22 11:10

Vincent Ramdhanie