0

I have created a class extending JComboBox. the model is set like this:

DefaultComboBoxModel<String> readoutModel = new DefaultComboBoxModel<String>(options.toArray(new String[options.size()]));
setModel(readoutModel);

The class implements a listener interface to listen for changes of another class (myModel). These changes might be not relevant at all for that combobox, it might contain selection changes and it might contain content changes for that combobox.

it's easy to change the selection like this:

@Override
public void modelChanged() {
    ...
    setSelectedItem(myModel.getSelectedReadOut());
}

but what if the content of the combobox needs to be changed? shall I replace the combobox model? would I have to interate over the items and compare them with the items present in myModel? I could also remove all items from the combobox model and then add item by item from myModel? (which would also happen if just the selection changes...).

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Antje Janosch
  • 1,154
  • 5
  • 19
  • 37
  • to posted question and with code maybe search for Mutable/AbstractComboBoxModel . – mKorbel Sep 23 '14 at 08:51
  • 1
    What ever you wanna show in the `Combobox` it has to come from the model. So if we need to filter the items in the combo box better get the `filtering done in the model` and pass the final list to the `Combobox` fro display. – Amarnath Sep 23 '14 at 10:24

1 Answers1

2

Three options to update your combo box when the underlying data is changed:

  • Exchange the model (replace with the new one)
  • Use a generic mutable model (such as DefaultComboBoxModel) and add/remove the data to reflect the changes
  • Create your own model implementation which is an Adapter to the actual data, and fire change events to reflect changes on the data.

The Adapter solution is quite easy to implement (ComboBoxModel, which is a ListModel), doesn't need to duplicate data and therefore does not need synchronization. Usually the best option, in my option.

Peter Walser
  • 15,208
  • 4
  • 51
  • 78
  • I wen't for the second option but I needed to mute the itemlistener as the repopulation of the combobox fired a selection changed event which caused an (unnecessary) change in myModel, which then fired a modelChanged-event and I got a nice cycle... – Antje Janosch Sep 26 '14 at 08:07