1.使用成员内部类方式实现窗口监听
java
ackage com.yundait.lesson03;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//主程序
public class TestWindow {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame {
public WindowFrame(){
setBackground(Color.blue);
setBounds(200,200,500,400);
setVisible(true);
addWindowListener(new MyWindowListener());
}
//创建窗口监听类,使用成员内部类方式实现。
class MyWindowListener extends WindowAdapter{
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
2.使用匿名内部类方式监听窗口
java
package com.yundait.lesson03;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindow01 {
public static void main(String[] args) {
new WindowsFrame01();
}
}
//创建我的窗口类
class WindowsFrame01 extends Frame{
//调用构造器方法进行初始化;
public WindowsFrame01(){
setBackground(Color.blue);
setBounds(200,200,500,400);
setVisible(true);
//添加窗口监听事件,
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}//使用匿名内部类方式监听窗口关闭
});
}
}
3.窗口监听可实现的常用功能
java
package com.yundait.lesson03;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindow01 {
public static void main(String[] args) {
new WindowsFrame01();
}
}
//创建我的窗口类
class WindowsFrame01 extends Frame{
//调用构造器方法进行初始化;
public WindowsFrame01(){
setBackground(Color.blue);
setBounds(200,200,500,400);
setVisible(true);
//添加窗口监听事件,
addWindowListener(new WindowAdapter() {
@Override //窗口被打开
public void windowOpened(WindowEvent e) {
System.out.println("windowOpened");
}
@Override //窗口正在关闭
public void windowClosing(WindowEvent e) {
System.out.println("windowClosing");
System.exit(0);
}
@Override //窗口被关闭
public void windowClosed(WindowEvent e) {
System.out.println("windowClosed");
}
@Override //窗口被激活
public void windowActivated(WindowEvent e) {
WindowsFrame01 source = (WindowsFrame01)e.getSource();
source.setTitle("窗口被激活了");
System.out.println("windowActivated");
}
});
}
}