I would create a class that implements the MutableComboBoxModel<T> interface and uses it as a TreeMap<T> or some other SortedMap<T> child element as the data core. I donβt think you would like to use HashMap , since the JComboBox model has to be ordered and the HashMap is not ordered.
The class also needs to extend AbstractListModel<E> to get ListModel functionality, automatically eliminating the need to maintain your own EventListenerList and give you two of the bottom four methods in my list above for free, as well as some fireXXX(...) data notification methods fireXXX(...) .
What you need to do is create the necessary methods dictated by the MutableComboBoxModel<T> API . That would mean introducing 12 methods,
- 4 from
MutableComboBoxModel<E> ,void addElement(E item)void insertElementAt(E item, int index)void removeElement(E obj)void removeElementAt(int index)
- 2 of
ComboBoxModel<E> ,E getSelectedItem()void setSelectedItem(E item)
- and 4 from
ListModel<E> ,void addListDataListener(ListDataListener listener) no need to write - part of AbstractListModelE getElementAt(int index)int getSize()void removeListDataListener(ListDataListener listener) does not need to be written - part of AbstractListModel
It should be helpful, I have to think.
Edit: When considering this more, I have a problem with insertElementAt(...) . Since I advocated SortedMap as the core of the model, you cannot add an element arbitrarily to the βon the mapβ position, since it is sorted in the βnaturalβ order. This works best using an ArrayList, Vector, or other similar collection, such as the model data core.
Change 2 . It is much better to use LinkedHashMap as suggested by Omid.
source share