在Java中处理和关闭窗口

时间:2011-01-19 15:59:42

标签: java user-interface awt

好吧,所以这可能是一个愚蠢的问题,但我是Java的新手,并且在我养成任何坏习惯之前尝试以正确的方式教自己。

无论如何,我昨晚编写的程序包括一个扩展Frame的自定义类和一个扩展Canvas的自定义类。 main()方法在canvas类中,我在那里创建了一个框架类的实例。问题是当程序检测到窗口关闭事件时,我无法丢弃框架,因为我似乎无法从主方法外部访问它。如果我尝试在main()之外定义它,那么我就无法在其中使用它。所以我最终跳过dispose()并只使用System.exit(0)。这好吗?它基本上是在做同样的事情吗?或者这是我需要解决的问题,如果有,任何想法如何?

非常感谢阅读,

科迪

3 个答案:

答案 0 :(得分:6)

您可以从事件的source属性获取对该框架的引用:

class MyWindowListener extends WindowAdapter {

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

}

或者,由于这是一个在构造函数中声明的匿名类(可能),您还可以访问封闭的实例,因此您也可以将其写为:

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

或者你可以使它更简单(因为你的WindowListener没有自己的方法叫做“dispose”):

public void windowClosing(WindowEvent e){
     dispose();
}

答案 1 :(得分:5)

不是一个愚蠢的问题。但是,由于垃圾收集器不是一个大问题,有时候当窗口关闭时你会想要执行一些清理工作。所以有些建议:

应该从Frame本身处理Window Closing事件。例如:

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

我建议你为main方法创建一个单独的类来调用Frame等。

答案 2 :(得分:0)

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

}

//在父窗口中     @override

 public void windowClosing(WindowEvent arg0) {

        // TODO Auto-generated method stub
        this.frame.disable();
    }
相关问题