2017-05-06 45 views
1

我创建了一个动作监听器,监听,如果有一个departingStop(组合框对象)的Java:添加相同的动作监听muliple组合框

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 
    } 
}); 

如何才能实现这一目标?谢谢

+0

这个动作监听器是匿名的,你需要的是被设置为两个 –

回答

3

可以监听分配给一个变量...

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

然后多次添加它...

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

谢谢大家做参考!将在8分钟内接受... –

2

上面评论,要实现一个匿名监听器您需要设置为两者的参考:

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

departingStop.addActionListener(foo); 
finalStop.addActionListener(foo); 
0

如果您的IDE难以设置在GUI组件rbitrary监听器,把常见的监听功能集成到一个单独的方法,并调用该方法从两个组合框听众:

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 
}