【发布时间】:2015-02-20 04:37:17
【问题描述】:
我会更多地了解e.getSource() 在ActionListener 类中的工作原理,
我的代码在这里:
public class ActionController implements ActionListener{
private MyButton theButton;
public void setTheButton(MyButton btn){
this.theButton = btn;
}
public void actionPerformed(ActionEvent e){
if(this.theButton == e.getSource()){
System.out.println(e.getSource().getName());
}
}
}
据我了解,e.getSource() 将返回对事件来源对象的引用。
现在我不明白为什么我不能通过这样做来调用源方法:
System.out.println(e.getSource().getName());
我只能通过调用 CLass 中的私有字段theButton,像这样:
System.out.println(this.theButton.getName());
虽然它已经是this.theButton == e.getSource() 我不明白为什么,有人可以解释更多吗?
补充说明,我为什么要这样做:
我可以制作一个将一些操作设置为多个按钮的 GUI,并且我想将 UI 代码和操作代码分成两个类。 我的目标是让 ActionController 成为中间人,在另一个类中调用函数(这些函数能够重用),同时它有一个链接按钮名称和函数的列表。
我已阅读this question,答案尝试在构造类时传递所有 ui 元素。而不是这样,我更喜欢通过在类构造之后调用方法来动态传入 ui 元素。
如果它能够调用e.getSource().getName(),这样做会很干净:
private String[] element_funtion_table;
public void actionPerformed(ActionEvent e){
String eleName = e.getSource().getName();
String ftnName = this.getLinkedFtn(eleName);
if(!ftnName.equals("")){
this.callFtn(ftnName);
}
}
(代码的一部分,你明白了)这使得管理起来很容易,因为
虽然我不能 e.getSource().getName() 我需要存储 MyButton 数组,而不仅仅是按钮的名称。
【问题讨论】:
标签: java