编写代码 TestWindowListener测试类


package com.xiang.lesson03;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

//窗口监听
public class TestWindowListener {
    public static void main(String[] args) {
        new WindowFrame();
    }
}

class WindowFrame extends Frame {
    public WindowFrame() {
        setVisible(true);
        setBackground(Color.blue);
        setBounds(100, 100, 300, 300);
//        addWindowListener(new MyWindowListener());

//        匿名内部类
        this.addWindowListener(new WindowAdapter() {
            @Override
//            关闭窗口
            public void windowClosing(WindowEvent e) {
                System.out.println("windowClosing");
                System.exit(0);
            }

            @Override
//            激活窗口
            public void windowActivated(WindowEvent e) {
                WindowFrame source = (WindowFrame) e.getSource();
                source.setTitle("被激活了");
                System.out.println("windowActivated");
            }
        });
    }

    //    监听器
//    内部类
    class MyWindowListener extends WindowAdapter {
        @Override
        public void windowClosing(WindowEvent e) {
            setVisible(false); //隐藏
            System.exit(0);
        }
    }
}

运行结果

GUI 窗口监听事件_java

GUI 窗口监听事件_内部类_02