<div class="iteye-blog-content-contain" style="font-size: 14px"></div>
e.getSource()方法依赖于事件对象。比如:JButton jb= new JButton("开始");中的事件对象就是jb。
e.getActionCommand()方法得到的是按钮上的字符串。比如:JButton jb = new JButton("开始");中返回的是字符串"开始"。
总结:用e.getSource()得到的是添加监听器的组件对象,而用e.getActionCommand()得到的是组件对象上的字符串。
/**
* 该代码是为了验证getSource()和getActionCommand()的区别
* 从程序的运行结果可以看出getSource()获取的是组件对象
* getActionCommand()获取的是组件上的字符串
* 具体分析见博客链接:http://1710127116.iteye.com/admin/blogs/2161725
*
*/
package 获取按钮对象;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class AtWho extends JFrame {
public void initUi(){
this.setSize(400, 300);
this.setLocationRelativeTo(null);
this.setLayout(new FlowLayout());
JButton jb=new JButton("ok");
this.add(jb);
jb.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("e.getActionCommand():"+e.getActionCommand());
System.out.println("e.getSource():"+e.getSource());
}});
this.setDefaultCloseOperation(3);//参数的作用:0:点击关闭按钮对话框不会被关闭;
//1:点击 关闭按钮对话框被立即关闭,但程序始终在开启状态;
//2:点击关闭按钮后对话框立即被关闭,但要几秒钟后程序才能结束;
//3:点击关闭按钮后对话框和程序都立即被关闭;其他数字将会报参数不合法的错误。
this.setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
AtWho aw=new AtWho();
aw.initUi();
}
}
程序运行结果:
e.getActionCommand():ok
e.getSource():javax.swing.JButton[,168,5,48x28,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@f8f7db,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=ok,defaultCapable=true]
显然,e.getSource()获取的是按钮对象!