Display dropdown for JComboBox use a Keystroke If the Selected Item Is Not Unique in Java

Description

The following code shows how to display dropdown for JComboBox use a Keystroke If the Selected Item Is Not Unique.

Example


//w w  w.  j  av a  2  s . c o m

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();
      }
    }
  }
}

The code above generates the following result.

Display dropdown for JComboBox use a Keystroke If the Selected Item Is Not Unique in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer