Question

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?

Was it helpful?

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

OTHER TIPS

You can extend JComboBox and init what you want in constructor

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top