GUI-AWT-窗口监听

2022/4/17 23:12:53

本文主要是介绍GUI-AWT-窗口监听,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

窗口监听

 1 package com.luckylu.gui;
 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.blue);
16         setBounds(200,200,300,200);
17         setVisible(true);
18         //addWindowListener(new MyWindowListener());
19         //this.addWindowListener(new WindowAdapter() { //this可加可不加
20         addWindowListener(new WindowAdapter() {
21             @Override
22             public void windowClosing(WindowEvent e) {
23                 setVisible(false);  //隐藏窗口:通过按钮,隐藏当前窗口
24                 System.exit(0);  //正常退出
25             }
26         });
27 
28 
29     }
30 
31     /* //内部类
32     class MyWindowListener extends WindowAdapter{
33         //快捷键 ctrl + o;
34         @Override
35         public void windowClosing(WindowEvent e) {
36             setVisible(false);  //隐藏窗口:通过按钮,隐藏当前窗口
37             //System.exit(0);  //正常退出
38         }
39     }
40      */
41 }

结果:

 

 

常用WINDOWS监听事件

 1 package com.luckylu.gui;
 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.blue);
16         setBounds(200,200,300,200);
17         setVisible(true);
18         this.addWindowListener(new WindowAdapter() { //匿名内部类
19 
20             @Override
21             public void windowClosing(WindowEvent e) {
22                 System.out.println("windowClosing");  //正在关闭中(常用)
23                 System.exit(0);
24             }
25 
26             @Override
27             public void windowActivated(WindowEvent e) {
28                 WindowFrame source = (WindowFrame) e.getSource();
29                 source.setTitle("窗口被激活");
30                 System.out.println("windowActivated");  //窗口被激活(常用)
31             }
32 
33 
34         });
35     }
36 }

 

结果:

 



这篇关于GUI-AWT-窗口监听的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程