📅  最后修改于: 2020-09-29 05:38:09             🧑  作者: Mango
我们可以通过在windowClosing()方法内调用dispose()或System.exit()来关闭AWT窗口或框架。在WindowListener接口和WindowAdapter类中找到windowClosing()方法。
WindowAdapter类实现WindowListener接口。它提供了WindowListener接口的所有7种方法的默认实现。要覆盖windowClosing()方法,可以使用WindowAdapter类或WindowListener接口。
如果实现WindowListener接口,则将不得不重写WindowListener接口的所有7种方法。因此最好使用WindowAdapter类。
有许多方法可以覆盖windowClosing()方法:
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class WindowExample extends Frame{
WindowExample(){
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
dispose();
}
});
setSize(400,400);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new WindowExample();
}
输出:
import java.awt.*;
import java.awt.event.*;
public class AdapterExample extends WindowAdapter{
Frame f;
AdapterExample(){
f=new Frame();
f.addWindowListener(this);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void windowClosing(WindowEvent e) {
f.dispose();
}
public static void main(String[] args) {
new AdapterExample();
}
}
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class WindowExample extends Frame implements WindowListener{
WindowExample(){
addWindowListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new WindowExample();
}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowClosing(WindowEvent e) {
dispose();
}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent arg0) {}
}