Displaying the Menu in a JComboBox Component Using a Keystroke If the Selected Item Is Not Unique
This example registers a key listener in a read-only combobox that
displays the menu if the newly selected item is not unique.
// Create a read-only combobox
String[] items = {"Ant", "Ape", "Bat", "Boa", "Cat"};
JComboBox cb = new JComboBox(items);
// Create and register the key listener
cb.addKeyListener(new MyKeyListener());
// This key listener displays the menu only if the pressed key
// does not select a new item or if the selected item is not unique.
class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
JComboBox cb = (JComboBox)evt.getSource();
// At this point, the selection in the combobox has already been
// changed; get the index of the new selection
int curIx = cb.getSelectedIndex();
// Get pressed character
char ch = evt.getKeyChar();
// Get installed key selection manager
JComboBox.KeySelectionManager ksm = cb.getKeySelectionManager();
if (ksm != null) {
// Determine if another item has the same prefix
int ix = ksm.selectionForKey(ch, cb.getModel());
boolean noMatch = ix < 0;
boolean uniqueItem = ix == curIx;
// Display menu if no matching items or the if the selection is not unique
if (noMatch || !uniqueItem) {
cb.showPopup();
}
}
}
}
Post a comment