Displaying the Menu in a JComboBox Component Using a Keystroke
By default, typing a key in a read-only combobox selects an item that
starts with the typed key. This example demonstrates how to display
the drop-down menu when a key is typed.
// Create a read-only combobox
String[] items = {"Ant", "Ape", "Bat", "Boa", "Cat", "Cow"};
JComboBox cb = new JComboBox(items);
// Create and register the key listener
cb.addKeyListener(new MyKeyListener());
// This key listener displays the menu when a key is pressed.
// To display the menu only if the pressed key matches or does not match an item,
// see Displaying the Menu in a JComboBox Component Using a Keystroke If the Selected Item Is Not Unique.
class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
JComboBox cb = (JComboBox)evt.getSource();
// Get pressed character
char ch = evt.getKeyChar();
// If not a printable character, return
if (ch != KeyEvent.CHAR_UNDEFINED) {
cb.showPopup();
}
}
}
Post a comment