简体   繁体   English

具有多个输入选项的ActionEvent e.getsource()

[英]ActionEvent e.getsource() with multiple input options

I am trying to create a decent looking solution for a problem I have. 我正在尝试为遇到的问题创建一个体面的解决方案。 I can explain in words, but the code will be clearer: 我可以用语言解释,但是代码会更清晰:

public void actionPerformed(ActionEvent e) {       
        if(e.getSource().equals(ClassA.getButtonOne()) ||
            e.getSource().equals(ClassB.getButtonOne())) {         
            ???????.setEnabled(false);          (class a or class b)
        }

Explanation: How can I change e.getSource() into the right class type, so I can perform methods on it? 说明:如何将e.getSource()更改为正确的类类型,以便可以对其执行方法? One extra detail: I am sure all methods in the if-statement possess the method I want to execute, in the example above 'setEnabled'. 一个额外的细节:在“ setEnabled”上面的示例中,我确定if语句中的所有方法都具有我要执行的方法。 I can solve the problem by creating multiple if-statements, but that would create duplicate code (especially since there will also be a class C and D in the future) . 我可以通过创建多个if语句来解决问题,但这会创建重复的代码(特别是因为将来还会有C和D类)。

If you need to use the same listener, the requirement looks like a visitor or double-dispatch pattern. 如果您需要使用相同的侦听器,则要求看起来就像一个访客双调度模式。 You should redirect back onto the source class eg 您应该重定向回到源类,例如

public void actionPerformed(ActionEvent e) {       
        Object source = e.getSource();
        if (source instanceof MySource) {
           ((MySource)source).executeOnEvent(e, this);
        }
         ....

This way you don't have to implement lots of 'if's (which is error prone and verbose, as you've identified). 这样,您不必实现大量的“ if”(如您所确定的,它容易出错且很冗长)。 You simply check the object type upon event receipt, and call back on it if appropriate. 您只需在事件接收后检查对象类型,然后在适当时对其进行调用。 Note that I call back in the above with the event and the object receiving the event. 请注意,我在上面用事件和接收事件的对象回叫。 You can choose, however, which parameters are important/relevant. 但是,您可以选择哪些参数是重要/相关的。

对每个可能的来源使用不同的侦听器实例,并完全避免问题。

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

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