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
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();
}
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.
This is used to close Jframe with an event handler.
current Jframe
public class LoginForm extends JFrame
{
LoginForm()
{
//Some code for Jframe and its components.
if(Condition)
disposewindow();
}
private void disposewindow()
{
WindowEvent closingEvent = new WindowEvent(LoginForm.this,
WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(closingEvent);
}
//you can can use for alternate of dispose()event and it post some event handler **Closing event** ,
// if we can use this closing event to open new window with conditions.
//It means closing child window with closing event, get this flag in main window to make main window as Disable or Enable state
}
//In parent window @Override
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
this.frame.disable();
}
精彩评论