本文概述
- 重写windowClosing()方法的不同方法
- 关闭AWT窗口示例1:匿名类
- 关闭AWT窗口示例2:扩展WindowAdapter
- 关闭AWT窗口示例3:实现WindowListener
WindowAdapter类实现WindowListener接口。它提供了WindowListener接口的所有7种方法的默认实现。要覆盖windowClosing()方法, 可以使用WindowAdapter类或WindowListener接口。
如果实现WindowListener接口, 则将不得不重写WindowListener接口的所有7种方法。因此最好使用WindowAdapter类。
重写windowClosing()方法的不同方法 有许多方法可以覆盖windowClosing()方法:
- 匿名班
- 通过继承WindowAdapter类
- 通过实现WindowListener接口
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();
}
【如何在Java中关闭AWT窗口】输出:
文章图片
关闭AWT窗口示例2:扩展WindowAdapter
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();
}
}
关闭AWT窗口示例3:实现WindowListener
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) {}
}
推荐阅读
- Java ItemListener接口
- Java AWT工具包
- Java AWT TextField
- Java AWT TextArea
- Java AWT滚动条
- Java AWT PopupMenu
- Windows 10的10大最佳Xbox 360模拟器推荐合集(你知道哪些())
- 13款用于在线评估的最佳开源考试软件推荐合集
- 如何将照片从Android传输到iPhone(实现方法分步指南)