需要设计一个ActionListener 的接口
package Test;
import java.awt.*;
import java.awt.event.*;
class ColorAction implements ActionListener{
private ActionExample frame; //用主类对象作为对象。翻遍两类之间联系
private Color bgColor;
public ColorAction(ActionExample btn,Color c){//带两个参数构造方法
frame = btn;
bgColor = c;
}
public void actionPerformed(ActionEvent e){
frame.setBackground(bgColor);
}
}
public class ActionExample extends Frame {
ActionExample() { ///构造函数
// TODO Auto-generated constructor stub
Panel panel = new Panel();
Button redButton = new Button("红色");
panel.add(redButton);
add(panel, "South");
//注册时间侦听器,同一个类的三个不同对象
redButton.addActionListener(new ColorAction(this, Color.red));
}
public static void main(String argc[]){
ActionExample myframe = new ActionExample();
myframe.setBounds(500, 400, 300, 200);
myframe.setVisible(true);
myframe.addWindowListener(new WindowAdapter() { //窗口体关闭
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}