窗体事件源和事件命令

package demo.event.swing;


import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class EventSourseTest {
public static void main(String[] args) {
new EventSourse();
}
}


class EventSourse extends SupperJFarme {
public EventSourse() {
super();
this.setTitle("事件源窗体改变");
add(new EventButtonJpanel());
}
}


class EventButtonJpanel extends JPanel implements ActionListener{


JButton yellow=null;
JButton red=null;
JButton green=null;
public EventButtonJpanel() {
yellow=new JButton("yellow");
red=new JButton("red");
green=new JButton("green");
yellow.addActionListener(this);
red.addActionListener(this);
green.addActionListener(this);
this.add(yellow);
this.add(red);
this.add(green);
}

//此两种方法均可以做到相同的事情,唯一美中不足,在面板有很多的按钮,会有很多的if... 对于维护增减了新的按钮需要改动源程序
public void actionPerformed(ActionEvent e) {

//事件源返回的是一个对象,第一种
/**Object source=e.getSource();


if(source.equals(yellow))
this.setBackground(Color.yellow);
else if(source.equals(red))
this.setBackground(Color.red);
else if(source.equals(green))
this.setBackground(Color.GREEN);*/
//第二种,返回的是执行的命令的文本
String text=e.getActionCommand();
System.out.println(text);
if(text.equals("yellow"))
this.setBackground(Color.yellow);
else if(text.equals("red"))
this.setBackground(Color.red);
else if(text.equals("green"))
this.setBackground(Color.GREEN);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值