Java-ActionEvent事件

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

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章