ActionListener 接口代码,可以看到e.getSource() 获得触发事件的对象
if(e instanceof MyEvent)//不关注事件源,而关注事件类型时,通过事件类型判断
if(e.getSource() instanceof MyEventSource)//类型已确定,关注事件来源时,通过事件源类型判断
getSource得到的组件的名称,而getActionCommand得到的是标签。
如:Button bt=new Button(“buttons”);
用getSource得到的是bt 而用getActionCommand得到的是:buttons
e.getSource() 返回的当前动作所指向的对象,包含对象的所有信息
e.getActionCommand() 返回的是当前动作指向对象的名称
例:
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
//定义发生ActionEvent 事件时要执行什么。当然,一个监听器是可以监听多个事件源触发的ActionListener的,所以通常都会先判断事件源
if(e.getSource() == myButtonOne){...}
else if(e.getSource()==myButtonTwo{...}
...
}
}
package com.liuyanzhao;
import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class Demo2 implements ActionListener {
JButton button_open ;
JButton button_close;
Label label;//这个地方不要用JLable,否则空白符不占位
Label label2;
public static void main(String[] args) {
Demo2 d = new Demo2();
d.go();
}
public void go() {
JFrame frame = new JFrame();
frame.setSize(300, 100);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
JPanel panel = new JPanel();
frame.add(panel);
label = new Label("灯状态:");
label2 = new Label(" ");
button_open = new JButton("开灯");
button_close = new JButton("关灯");
button_open.addActionListener(this);
button_close.addActionListener(this);
panel.add(label);
panel.add(label2);
panel.add(button_open);
panel.add(button_close);
}
@Override
public void actionPerformed(ActionEvent e) {
//方法一:getActionCommand
// if(e.getActionCommand()=="开灯") {
// label2.setBackground(Color.red);
// button_open.setEnabled(false);
// button_close.setEnabled(true);
// } else if(e.getActionCommand()=="关灯") {
// label2.setBackground(Color.black);
// button_close.setEnabled(false);
// button_open.setEnabled(true);
// }
//方法二:getSource
if(e.getSource()==button_open) {//button_open不要加引号
label2.setBackground(Color.red);
button_open.setEnabled(false);
button_close.setEnabled(true);
} else if(e.getSource()==button_close) {//button_closen不要加引号
label2.setBackground(Color.black);
button_close.setEnabled(false);
button_open.setEnabled(true);
}
}
}