【问题标题】:Java: Adding the same action listener to muliple combo boxesJava:将相同的动作侦听器添加到多个组合框
【发布时间】:2017-05-06 11:45:06
【问题描述】:

我创建了一个动作监听器,它监听 departingStop(组合框对象)是否有任何变化

departingStop.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent arg0) {
          //Lots of code here
     }
});

我还想将此动作侦听器添加到另一个组合框 (finalStop),而不必像这样创建单独的侦听器:

finalStop.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent arg0) {
          //Lots of code here
     }
});

如何做到这一点?谢谢

【问题讨论】:

  • 这个动作监听器是匿名的,你需要一个设置为两者的引用

标签: java callback actionlistener anonymous-types


【解决方案1】:

您可以将侦听器分配给变量...

ActionListener listener = new ActionListener() {
     public void actionPerformed(ActionEvent arg0) {
          //Lots of code here
     }
};

然后多次添加...

departingStop.addActionListener(listener);
finalStop.addActionListener(listener);

【讨论】:

    【解决方案2】:

    如上所述,您正在实现一个匿名侦听器,您需要一个设置为两者的引用:

    ActionListener foo = new ActionListener() {
         public void actionPerformed(ActionEvent arg0) {
              //Lots of code here
         }
    };
    
    departingStop.addActionListener(foo);
    finalStop.addActionListener(foo);
    

    【讨论】:

      【解决方案3】:

      如果您的 IDE 难以在 GUI 组件上设置任意侦听器,请将通用侦听器功能放入单独的方法中,并从两个组合框的侦听器中调用该方法:

      departingStop.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent arg0) {
                commonGutsOfListener(arg0);
           }
      });
      
      departingStop.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent arg0) {
                commonGutsOfListener(arg0);
           }
      });
      
      private void commonGutsOfListener(ActionEvent arg0){
            //Lots of code here
      }
      

      【讨论】:

        猜你喜欢
        • 2018-06-05
        • 1970-01-01
        • 2015-11-01
        • 1970-01-01
        • 2020-06-10
        • 2011-08-21
        • 2012-08-20
        • 1970-01-01
        • 2019-09-23
        相关资源
        最近更新 更多