窗口监听:
1 package com.gui.lesson3;
2
3 import java.awt.*;
4 import java.awt.event.WindowAdapter;
5 import java.awt.event.WindowEvent;
6
7 public class TestWindow {
8 public static void main(String[] args) {
9 new WindowFrame();
10 }
11 }
12
13 class WindowFrame extends Frame {
14 public WindowFrame() {
15 setBackground(Color.green);
16 setBounds(100, 100, 200, 200);
17 setVisible(true);
18 addWindowListener(new MyWindowListener());
19 }
20
21 //内部类
22 //WindowListener要重写方法太多了,所以我们继承它的实现类,WindowAdapter,选择要重写的方法即可
23 class MyWindowListener extends WindowAdapter {
24 @Override
25 public void windowClosing(WindowEvent e) {
26 setVisible(false);//隐藏窗口
27 //System.exit(0);//0是正常退出,1是关闭有异常的程序
28 }
29 }
30 }
View Code
测试两个常用的事件:
1 package com.gui.lesson3;
2
3 import java.awt.*;
4 import java.awt.event.WindowAdapter;
5 import java.awt.event.WindowEvent;
6
7 public class TestWindow {
8 public static void main(String[] args) {
9 new WindowFrame();
10 }
11 }
12
13 class WindowFrame extends Frame {
14 public WindowFrame() {
15 setBackground(Color.green);
16 setBounds(100, 100, 200, 200);
17 setVisible(true);
18 addWindowListener(
19 //推荐使用,匿名内部类
20 new WindowAdapter() {
21 //关闭窗口
22 @Override
23 public void windowClosing(WindowEvent e) {
24 System.out.println("windowClosing");
25 System.exit(0);
26 }
27
28 //激活窗口:离开窗口后,会变成灰色,重新进入后,会显示正常的
29 @Override
30 public void windowActivated(WindowEvent e) {
31 WindowFrame source = (WindowFrame) e.getSource();
32 source.setTitle("人呢,快回来");
33 System.out.println("windowActivated");
34 }
35 });
36 }
37 }
View Code