2011-01-19 97 views
4

好的,这可能是一个愚蠢的问题,但我是Java的新手,试图在我养成任何不良习惯之前以正确的方式教导自己。在Java中处理和关闭窗口

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

感谢这么多读书,

科迪

+0

System.exit(0)终止正在运行的JVM,所以要小心t帽子。这可能不仅仅是你的应用程序在该jvm中运行。 – fmucar 2011-01-19 16:22:41

回答

5

你可以在框架上的参考,从的了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没有所谓的 “处置” 它自己的方法):

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

感谢您的解释。这样做更有意义。我从未想过将getSource的输出作为一个框架并使用它。 – Keysmack 2011-01-21 06:12:06

5

不是一个愚蠢的问题。但是,由于垃圾收集器不是一个很大的问题,因此有时您会希望在窗口关闭时执行一些清理操作。所以一些建议:

窗户关闭事件应该从框架本身处理。例如:

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

而且我会建议你创建你的主要方法,一个单独的类,将调用框架等

+0

感谢您的回复。我想我会尝试为我的主要方法使用一个单独的类。这种方式似乎更清洁。 – Keysmack 2011-01-21 06:14:52

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(); 
    }