//事件监听机制
import java.awt.*;
import java.awt.event.*;
public class TestEvent {
public static void main(String[] args) {
Frame f = new Frame("Test");
Button b = new Button("Press Me!");
Monitor bh = new Monitor(); //实现了某种监听器接口的类的对象
b.addActionListener(bh); //注册
f.add(b, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
}
//实现了某种监听器接口的类
class Monitor implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("A button has been pressed");
}
}
import java.awt.*;
import java.awt.event.*;
public class TestActionEvent {
public static void main(String[] args) {
Frame f = new Frame("Test");
Button b1 = new Button("Start");
Button b2 = new Button("Stop");
//一个监听器类被两个button监听
Monitor2 bh = new Monitor2();
b1.addActionListener(bh);
b2.addActionListener(bh);
b2.setActionCommand("Game over");
f.add(b1,"North");
f.add(b2,"Center");
f.pack();
f.setVisible(true);
}
}
class Monitor2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
System.out.println("A button has been pressed," +
"the relative info is:\n" + e.getActionCommand());
}
}