要把实现了某种接口的类的对象注册到事件源对象上
eg1:
import java.awt.*;
import java.awt.event.*;
public class A implements ActionListener{
public static void main(String args[]) {
Frame f = new Frame("Test");
Button b1 = new Button("Start");
Button b2 = new Button("Stop");
b1.addActionListener(this);
b2.addActionListener(this);
b2.setActionCommand("game over");
f.add(b1,"North");
f.add(b2,"Center");
f.pack();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println("a button has been pressed," +
"the relative info is:\n " + e.getActionCommand());
}
}
---------会报错----------------------------------------------------
正确的应该是:eg2:
import java.awt.*;
import java.awt.event.*;
public class A implements ActionListener{
public static void main(String args[]) {
Frame f = new Frame("Test");
Button b1 = new Button("Start");
Button b2 = new Button("Stop");
A aa=new A();
b1.addActionListener(aa);
b2.addActionListener(aa);
b2.setActionCommand("game over");
f.add(b1,"North");
f.add(b2,"Center");
f.pack();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println("a button has been pressed," +
"the relative info is:\n " + e.getActionCommand());
}
}