在frame上添加事件,一定要把所有函数重载吗?下面是我写的一个例子,如果我不把这些重载完,就提示错误,请大家指教一下:frame2.addWindowListener(new WindowListener()
{
public void windowClosing(WindowEvent e)
{
frame2.dispose();
}
public void windowDeactivated(WindowEvent e) {}
public void windowActivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowClosed(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
});还有,我这个是匿名内部类写的,提示说要吧上面的 frame2 这个变量设置为final 才能编译成功,为什么呢?
{
public void windowClosing(WindowEvent e)
{
frame2.dispose();
}
public void windowDeactivated(WindowEvent e) {}
public void windowActivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowClosed(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
});还有,我这个是匿名内部类写的,提示说要吧上面的 frame2 这个变量设置为final 才能编译成功,为什么呢?
你使用WindowAdapter代替WindowListener,然后重载你需要的函数。
匿名内部类只能访问final变量。
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyFrame extends Frame{
public MyFrame() {
this.setSize(400, 500);
this.setVisible(true);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String[] args) {
new MyFrame();
}
}