
100
|
Chapter 2, Lists and Combos
#20 Create a Collections-Aware JComboBox
HACK
The MapComboBoxModel accepts a collection in its constructor—this time a
Map—saving it for later reference. To maintain the order of the keys, the class
uses a
List called index. The constructor calls buildIndex( ) to populate the
List with the Map’s set of keys, and then sets the selected item—just like in
the
List version. getElementAt( ) uses the index to get the display values and
getSize( ) uses the size of the Map itself.
actionPerformed( ) is different from the List version and calls buildIndex( )
before fireUpdate( ). This ensures that the index is always in sync with the
underlying map and that the
JComboBox reflects that. There is no implemen-
tation of
fireUpdate( ) or managing the listeners because the parent class,
ListComboBoxModel, takes care of those.
index = new ArrayList( );
buildIndex( );
if(index.size( ) > 0) {
selected = index.get(0);
}
}
protected void buildIndex( ) {
index = new ArrayList(map_data.keySet( ));
}
public Object getElementAt(int i) {
return index.get(i);
}
public int getSize( ) {
return map_data.size( );
}
public void actionPerformed(ActionEvent evt) {
if(evt.getActionCommand( ).equals("update")) {
buildIndex( );
fireUpdate( );
}
}
public Object getValue(Object selectedItem) {
return map_data.get(selectedItem);
}
public Object getValue(int selectedItem) {
return getValue(index.get(selectedItem)); ...