Chapter 7. Lists and Combo Boxes
7.5 The JList Class
7.7.1 The Key Selection Manager
With combo boxes, you have the ability to map keystrokes to item selections in the list. In order to do this, you can create an object that implements the internal interface
JComboBox.KeySelectionManager. This interface contains only one method:
Invoked by the JComboBox component after receiving a keyboard event while the list popup
is shown. The most recent character pressed, as well as the model for the combo box, are provided. The method must return the index of the list element that should be highlighted in the combo box, or -1 if a selection cannot be determined. Note that this procedure is
equivalent to moving the mouse across the list; hence, if the mouse pointer is anywhere inside the list, this procedure will not work.
Here is a short code excerpt that uses a key selection manager to map the numerals 0-9 on the keyboard to the first ten elements in the combo box list:
class myKeySelectionManager implements JComboBox.KeySelectionManager {
public int selectionForKey(char aKey, ComboBoxModel aModel) { if ((aKey >= '0') && (aKey <= '9'))
return (aKey - '0'); else
return -1; }
}
You can install the key selection manager using the setKeySelectionManager() method of JComboBox:
myComboBox.setKeySelectionManager(new myKeySelectionManager());
And that's all there is to it!
7.7.1.1 Properties
Table 7.14 shows the properties that can be found in the JComboBox component. As we mentioned
earlier, the editable property defines whether the text field of the combo box allows text to be
manually entered. The lightWeightPopupEnabled property allows you to specify whether
JComboBox should use a lightweight component to draw the list popup. The popupvisible property
controls whether the popup associated with the combo box is visible. The maximumRowCount
property represents the total amount of list elements that can be displayed in the popup. If the list contains more than maximumRowCount, it uses a scrollbar for navigation.
Table 7.14, JComboBox Properties
Property Data Type get is set bound Default Value
UI ComboBoxUI from L&F
UIClassID* String "ComboBoxUI"
model ComboBoxModel JComboBox.DefaultComboBoxModel()
accessibleContext AccessibleContext JComboBox.AccessibleJComboBox()
actionCommand String "comboBoxChanged"
editable boolean false
editor ComboBoxEditor ComboBoxEditor()
enabled* boolean true
focusTraversable* boolean false
itemAt (indexed) Object null
itemCount int 0
keySelectionManager JComboBox.Key-SelectionManager JComboBox.DefaultKeySelectionManager(
maximumRowCount int 8
opaque* boolean true
popupVisible boolean
renderer ListCellRenderer
selectedIndex int -1
selectedItem Object null
selectedObjects Object[] null
See also properties from the JComponent class (xref linkend="SWING-CH-3-TABLE-10"/>)
The following properties mimic those in JList: the selectedItem property represents the object
currently selected in the combo box. If you call the setSelectedItem() method with an object that
does not exist, the first object in the list is selected instead. The selectedIndex property gives the
index of the selected item, or -1 if there is none. The selectedObjects property holds an array of
size 1 — the object currently selected. The getSelectedObjects() method is present to provide
backward compatibility with the AWT Choice component. The read-only itemCount property tells
how many elements are currently in the combo box's list.
The enabled property overrides that of the java.awt.Component class. If the property is set to false, the method prevents the user from selecting items from the list and typing text into the text
field or editor. The opaque property, on the other hand, is always set to true. This indicates that the
component is opaque at all times. Finally, the focusTraversable property is set to false,
overriding the isFocusTraversable() method of JComponent. This tells Swing not to traverse
focus onto the JComboBox itself, but rather to skip directly to the text field or editor inside the
combo box.
The actionCommand property is coupled to an ActionEvent that is fired when the user makes a
selection inside the list. The actionCommand typically contains a string-based representation of the
item that was selected.
7.7.1.2 Events
Combo boxes fire both an ItemEvent and an ActionEvent when the selection in the list has
changed. The ItemEvent is fired when there is a change in the current selection of the list, from any
source. The ActionEvent is fired when the user explicitly makes a selection; it is coupled with the actionCommand property shown above. (Note that the actionCommand does not by default tell you
the item that was selected.) The ItemEvent and its listener list maintain backward compatibility
with the ItemSelectable interface of AWT 1.1.
public void addItemListener(ItemListener aListener)
public void removeItemListener(ItemListener aListener)
Add or remove an ItemListener from the list. These methods maintain backward
compatibility with the ItemSelectable interface of AWT 1.1.
public void addActionListener(ActionListener l)
public void removeActionListener(ActionListener l)
Add or remove an ActionListener for ActionEvents sent when the user makes a
selection.
Can be called to signify that an item selection of the combo box has changed.
protected void fireActionEvent()
Can be called to signify that the user has made a new selection.
protected void selectedItemChanged()
Equivalent to fireItemStateChanged().
7.7.1.3 Constructors
public JComboBox(ComboBoxModel aModel)
Initializes its items from an existing ComboBoxModel.
public JComboBox(Object items[])
Creates a JComboBox using the items specified in the array.
public JComboBox(Vector items)
Creates a JComboBox using the items specified in the Vector passed in.
public JComboBox()
Creates an empty JComboBox using the DefaultComboBoxModel as its data model.
7.7.1.4 Methods
public void updateUI()
Called by the UIManager when the look-and-feel of the component has changed.
public void showPopup()
Raises the popup that contains the combo box list.
public void hidePopup()
Lowers the popup that contains the combo box list.
public void configureEditor(ComboBoxEditor anEditor, Object anItem)
Initializes the specified ComboBoxEditor with the object passed in.
7.7.1.5 List Methods
public void addItem(Object anObject)
Adds a specific object to the end of the list. This method must work in conjunction with a
MutableComboBoxModel; otherwise, an error will be thrown.
Inserts an object into the list after the index specified. This method must work in conjunction with a MutableComboBoxModel; otherwise, an error will be thrown.
public void removeItem(Object anObject)
Removes the specified object from the list after the specified index. This method must work in conjunction with a MutableComboBoxModel; otherwise, an error will be thrown.
public void removeItemAt(int anIndex)
Removes an object from the list at the specified index.
public void removeAllItems()
Removes all items from the list. This method must work in conjunction with a
MutableComboBoxModel; otherwise, an error will be thrown.
7.7.1.6 Key Selection
protected JComboBox.KeySelectionManager createDefaultKeySelectionManager()
Returns a new instance of the default key selection manager. This selection manager matches keystrokes against the first character of each item in the list starting with the first item below the selected item (if there is one).
public boolean selectWithKeyChar(char keyChar)
Attempts to select a list item that corresponds to the character passed in. If the method is successful, it returns true. If there is no list item that corresponds to that character, the
method returns false.
7.7.1.7 Internal Methods
Because the JComboBox maintains both a text field and a list, it implements several methods that are
not intended to be invoked by the user.
public void processKeyEvent(KeyEvent e)
Overrides processKeyEvent() in JComponent. The method calls hidePopup() if the user
presses the TAB key. It should not be invoked by the programmer.
public void actionPerformed(ActionEvent e)
Monitors internal action events from the embedded list component and must be public. It should not be invoked or overridden by the programmer.
public void contentsChanged(ListDataEvent e)
Monitors model events from the list component and must be public. It should not be invoked or overridden by the programmer.
This method is invoked when an interval of list items has been added to the list. It should not be called by the programmer.
public void intervalRemoved(ListDataEvent e)
This method is invoked when an interval of list items has been removed from the list. It should not be called by the programmer.