【问题标题】:Why I can't call method of returns of e.getSource()?为什么我不能调用 e.getSource() 的返回方法?
【发布时间】: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


    【解决方案1】:

    你需要将它投射到你的班级MyButton

    if(e.getSource() instanceof MyButton) {
        MyButton btn = (MyButton)e.getSource();
        System.out.println(btn.getName());
    }
    

    e.getSource() 返回Object 类型。在类Object 中没有名为getName() 的方法。因此编译器抱怨它。

    已编辑

    public void actionPerformed(ActionEvent e){
        if(e.getSource() instanceof MyButton) {
            MyButton btn = (MyButton)e.getSource();
            String ftnName = this.getLinkedFtn(btn.getName());
            if(!ftnName.equals("")){
                this.callFtn(ftnName);
            } else {
                System.out.println("unknown ftnName");
            }
        } else {
            System.out.println("unknown source");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-24
      • 2015-01-02
      • 2020-02-11
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 2011-12-09
      • 2013-07-09
      相关资源
      最近更新 更多