Search code examples
javajcomboboxpropertychangelistener

Add PropertyChangeListener to to multiple JComboBoxes


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?


Solution

  • 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