Java Reference
In-Depth Information
■
Tip
To programmatically deselect the current choice of a
JComboBox
, call
setSelectedIndex()
with an
argument of -1.
Listening to Keyboard Events with a KeySelectionManager
The
JComboBox
has a public inner interface that's fairly important.
KeySelectionManager
, and its
default implementation, manages selection from the keyboard of items within the
JComboBox
.
The default manager locates the next element that corresponds to the pressed key. It has
memory, so if you have entries that start with similar prefixes, users can continue typing until
there is enough of a match to be unique. If you don't like this behavior, you can either turn it
off or create a new key selection manager.
■
Note
The
KeySelectionManager
works only in combo boxes that are not editable.
If you want to turn off the key-selection capabilities, you can't do so by simply setting the
keySelectionManager
property to
null
. Instead, you must create an implementation of the
interface with an appropriate method. The single method of the interface is
public int
selectionForKey(char aKey, ComboBoxModel aModel)
. In the event the pressed key doesn't
match any elements, the routine needs to return -1. Otherwise, it should return the position of
the matched element. So, to ignore keyboard input, the routine should always return -1, as
shown here:
JComboBox.KeySelectionManager manager =
new JComboBox.KeySelectionManager() {
public int selectionForKey(char aKey, ComboBoxModel aModel) {
return -1;
}
};
aJcombo.setKeySelectionManager(manager);
Listening to JComboBox Events with an ActionListener
The primary means of listening for selection events is through an
ActionListener
, possibly set
with
setAction(Action)
. It will tell you when an element has been selected within a
JComboBox
.
Unfortunately, the listener doesn't know which element is selected.
■
Note
Setting the
ActionListener
through
setAction(Action)
also configures the tooltip text and the
enabled
state of the
JComboBox
based on the
Action
.