将 PropertyChangeListener 添加到多个 JComboBox
我有一个带有 JComboBoxes
的表,并且想要向每个 JComboBox
添加一个 PropertyChangeListener
,因为 ComboBox 的某些选择必须更改其他 ComboBox 的可选择项JComboBox
。
我无法手动添加所有这些侦听器,因为它们的数量非常多。
我正在使用数组初始化 ComboBox,因此在创建 JComboBox
时我已经尝试添加侦听器,如下所示:
comboBox[i].addPropertyChangeListener(new PropertyChangeListener()
但它不起作用,因为字段变量 i
是不是最终的,我需要这个变量。
如何将此变量存储在组合框中,或者是否有其他可能性来解决此问题?
i have a Table with JComboBoxes
and want to add aPropertyChangeListener
to every single JComboBox
, because some selections of ComboBoxes have to change the selectables of other JComboBoxes
.
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:
comboBox[i].addPropertyChangeListener(new PropertyChangeListener()
But it didnt work because the field variable i
is not final and I need this variable.
How can I store this variable in the comboBox or is there a other possibility to solve this Problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您可以创建所有这些组合框,那么您还可以手动添加“所有这些侦听器”。有多种选择:
i
传递给该侦听器(通过匿名类、内部类或完全成熟的类)或通过Francis Upton 在他的回答中建议的最终副本i
来检索事件起源的组合框,您还可以调用event#getSource
(这是在ActionEvent
上都可用以及PropertyChangeEvent
,因为您的问题不清楚侦听器的类型)。在这种情况下,您可以仅创建侦听器一次,也可以为每个组合框创建一个侦听器If you can create all those comboboxes, then you can also add 'all those listeners' manually. There are several options:
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 answeri
only to retrieve the combobox from which the event originated, you can also callevent#getSource
(which is available on both theActionEvent
as well as on thePropertyChangeEvent
since your question is not clear about the type of listener). In this case you can either create the listener only once, or create one listener for each combobox您可以扩展 JComboBox 并在构造函数中初始化您想要的内容
You can extend JComboBox and init what you want in constructor
在循环中,您可以将 i 复制到另一个最终变量,并在
ActionListener
中引用该最终变量。In your loop you can copy i to another final variable, and refer to that final variable in your
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).