将 PropertyChangeListener 添加到多个 JComboBox

发布于 2024-12-24 01:07:53 字数 471 浏览 5 评论 0原文

我有一个带有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

停滞 2024-12-31 01:07:53

如果您可以创建所有这些组合框,那么您还可以手动添加“所有这些侦听器”。有多种选择:

  • 每次创建新的组合框时创建一个新的侦听器,并将索引 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:

  • 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
  • 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). In this case you can either create the listener only once, or create one listener for each combobox
深居我梦 2024-12-31 01:07:53

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

You can extend JComboBox and init what you want in constructor

旧瑾黎汐 2024-12-31 01:07:53

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

In your loop you can copy i to another final variable, and refer to that final variable in your ActionListener.

并安 2024-12-31 01:07:53

不要使用匿名类,而是创建一个实现您关心的接口的真实类。这样您就可以传递组合框索引(如果您需要的话,甚至可以传递组合框实例)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文