需要設計一個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);
}
});
}
}