事件监听:
当某个事情发生的时候,干什么?比如说,点击按钮,它需要发送一条消息;按下键盘上键,它需要往上走;按下键盘下键,它需要往下走。它就属于一个监听,所以监听就有鼠标监听、键盘监听。。。
案例一:按下按钮,触发一些事件


1 package com.gui.lesson2;
2
3 import java.awt.*;
4 import java.awt.event.ActionEvent;
5 import java.awt.event.ActionListener;
6 import java.awt.event.WindowAdapter;
7 import java.awt.event.WindowEvent;
8
9 public class TestActionEvent {
10 public static void main(String[] args) {
11 //按下按钮,触发一些事件
12 Frame frame = new Frame();
13 Button button = new Button();
14
15 //因为,addActionListener()需要一个 ActionListener ,所以我们需要构造一个 ActionListener,
16 //怎么构造呢?接口就去写实现类,如果是父类就去继承么。
17
18 MyActionListener myActionListener = new MyActionListener();
19 button.addActionListener(myActionListener);
20
21 //把按钮添加进去,然后到中间
22 frame.add(button, BorderLayout.CENTER);
23 //没设置大小,让它自适应
24 frame.pack();
25 //关闭窗口
26 windowsClose(frame);
27 //可见
28 frame.setVisible(true);
29
30 }
31
32 //关闭窗口的事件
33 public static void windowsClose(Frame frame) {
34 frame.addWindowListener(new WindowAdapter() {
35 @Override
36 public void windowClosing(WindowEvent e) {
37 System.exit(0);
38 }
39 });
40 }
41 }
42
43 //事件监听
44 class MyActionListener implements ActionListener {
45
46 @Override
47 public void actionPerformed(ActionEvent e) {
48 System.out.println("aaa");
49 }
50 }
案例二:多个按钮,共享一个事件类


1 package com.gui.lesson2;
2
3 import java.awt.*;
4 import java.awt.event.ActionEvent;
5 import java.awt.event.ActionListener;
6 import java.awt.event.WindowAdapter;
7 import java.awt.event.WindowEvent;
8
9 public class TestActionEvent {
10 public static void main(String[] args) {
11 //按下按钮,触发一些事件
12 Frame frame = new Frame();
13 Button button = new Button();
14
15 //因为,addActionListener()需要一个 ActionListener ,所以我们需要构造一个 ActionListener,
16 //怎么构造呢?接口就去写实现类,如果是父类就去继承么。
17
18 MyActionListener myActionListener = new MyActionListener();
19 button.addActionListener(myActionListener);
20
21 //把按钮添加进去,然后到中间
22 frame.add(button, BorderLayout.CENTER);
23 //没设置大小,让它自适应
24 frame.pack();
25 //关闭窗口
26 windowsClose(frame);
27 //可见
28 frame.setVisible(true);
29
30 }
31
32 //关闭窗口的事件
33 public static void windowsClose(Frame frame) {
34 frame.addWindowListener(new WindowAdapter() {
35 @Override
36 public void windowClosing(WindowEvent e) {
37 System.exit(0);
38 }
39 });
40 }
41 }
42
43 //事件监听
44 class MyActionListener implements ActionListener {
45
46 @Override
47 public void actionPerformed(ActionEvent e) {
48 System.out.println("aaa");
49 }
50 }
51
52 结果:
53 按钮被点击了:msg-start
54 按钮被点击了:msg-button2-stop