Mega Code Archive

 
Categories / Java Tutorial / Swing
 

Displaying the Menu in a JComboBox Component Using a Keystroke If the Selected Item Is Not Unique

import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JComboBox; public class Main {   public static void main(String[] argv) throws Exception {     String[] items = { "A", "A", "B", "B", "C" };     JComboBox cb = new JComboBox(items);     // Create and register the key listener     cb.addKeyListener(new MyKeyListener());   } } class MyKeyListener extends KeyAdapter {   public void keyPressed(KeyEvent evt) {     JComboBox cb = (JComboBox) evt.getSource();     int curIx = cb.getSelectedIndex();     char ch = evt.getKeyChar();     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();       }     }   } }