繁体   English   中英

当 ActionListener 位于不同的 class 时,如何访问 ActionEvent 的源?

[英]How do I access the source of an ActionEvent when the ActionListener is located in a different class?

我无法理解这一点。 我第一次尝试遵循 MVC 模式,但现在无法访问 ActionEvent 的源,因为 ActionListener 位于不同的 class 中。 但是让代码说话......

在“视图”中:

// ControlForms.java

...

private JPanel createSearchPanel() throws SQLException {

...

comboBoxCode = new JComboBox(); // Field comboBoxCode -> JComboBox()
    SwingUtilities.invokeLater(new Runnable() {  
        public void run() {  
            AutoCompleteSupport<Object> support = AutoCompleteSupport.install(
comboBoxCode, GlazedLists.eventListOf(jnlCodeArray));
        }  
    });  // Auto-Complete comboBox from GlazedLists

...

public void setComboListener(ComboListener comboListener) {
    comboBoxCode.addActionListener(comboListener);
}

...

}

然后,在我所说的 controller 中,我有两个不同的类:

// Controller.java

    public MyController() throws SQLException {
...
    addListeners();
}

...

    private void addListeners(){
    View view = getView();
    getView().getControlForm().setComboListener(new ComboListener());

}

public class ComboListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
    System.out.println("ComboBox listened to! e = " + e.toString());
}
}

现在, e显然没有给出变量的名称(目前我希望它会),所以我if测试e.getSource()

因此,我的问题是:是否一种方法可以查询(例如,通过if )e 的来源,或者b)一种不太复杂的方法来获取变量名?

非常非常感谢您的见解和提示!

为什么需要变量名? 为什么不能像这样进行事件处理

public class ComboListener implements ActionListener 
{
    public void actionPerformed(ActionEvent e) 
    {
        JComboBox source = (JComboBox)e.getSource();

        //do processing here
    }
}

我认为,如果您需要根据变量名进行处理,显然您需要针对不同的组合框使用不同的侦听器。

通常,只有两种情况应该使用这样的侦听器:a)您将以相同的方式处理一组对象的某个事件,或者 b)您只将侦听器用于一个 object。 在后一种情况下,无论如何我宁愿在本地处理事件。

也就是说,对您的问题的直接回答是:您不必检查ActionListener实现内部以查看适当的 object 是否是事件的来源; 您应该只将ActionListener添加到那个 object。

最后一点:在不知道您的架构细节的情况下......通常,MVC 会将所有事件处理视为视图的一部分(它减少了耦合),并且视图将传递命令或方法调用或您自己的事件(即,不是 Swing 的) 到 Controller。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM