简体   繁体   English

将PropertyChangeListener添加到多个JComboBoxes

[英]Add PropertyChangeListener to to multiple JComboBoxes

i have a Table with JComboBoxes and want to add a PropertyChangeListener to every single JComboBox , because some selections of ComboBoxes have to change the selectables of other JComboBoxes . 我有一个带有JComboBoxes的表,并想向每个JComboBox添加一个PropertyChangeListener ,因为ComboBoxes的某些选择必须更改其他JComboBoxes的selectables。

I can't add all those listeners manually because there are very much of them. 我不能手动添加所有这些侦听器,因为其中有很多。

I'm initializing the ComboBoxes with an array, so i already tried to add the listener when I create the JComboBox like this: 我正在使用数组初始化ComboBoxes,因此在创建JComboBox时,我已经尝试添加侦听器,如下所示:

comboBox[i].addPropertyChangeListener(new PropertyChangeListener()

But it didnt work because the field variable i is not final and I need this variable. 但这没有用,因为字段变量i不是最终变量,我需要此变量。

How can I store this variable in the comboBox or is there a other possibility to solve this Problem? 如何将这个变量存储在comboBox中,或者还有其他方法可以解决此问题?

If you can create all those comboboxes, then you can also add 'all those listeners' manually. 如果您可以创建所有这些组合框,则还可以手动添加“所有这些侦听器”。 There are several options: 有几种选择:

  • You create a new listener each time you create a new combobox, and pass that index i to that listener (either by anonymous class, inner class, or fully fledged class) or by making a final copy as Francis Upton suggested in his answer 您每次创建一个新的组合框时都会创建一个新的侦听器,并将该索引i传递给该侦听器(通过匿名类,内部类或完全成熟的类),或者按照弗朗西斯·厄普顿在答案中的建议进行最终复制
  • If you need that i only to retrieve the combobox from which the event originated, you can also call event#getSource (which is available on both the ActionEvent as well as on the PropertyChangeEvent since your question is not clear about the type of listener). 如果你需要i只检索该事件起源组合框,您也可以拨打event#getSource (它可同时在ActionEvent以及在PropertyChangeEvent ,因为你的问题是不清楚监听器的类型)。 In this case you can either create the listener only once, or create one listener for each combobox 在这种情况下,您可以只创建一次侦听器,也可以为每个组合框创建一个侦听器

您可以扩展JComboBox并在构造函数中初始化所需的内容

在循环中,您可以将i复制到另一个最终变量,然后在ActionListener引用该最终变量。

Instead of using an anonymous class, make a real class that implements the interface you care about. 代替使用匿名类,创建一个实现您所关心的接口的真实类。 That way you can pass the combobox index (or even the combobox instance if that is all you need). 这样,您可以传递组合框索引(如果需要的话甚至可以传递组合框实例)。

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

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