Java Swing Tutorial - Java JComboBox .getKeySelectionManager ()








Syntax

JComboBox.getKeySelectionManager() has the following syntax.

public JComboBox.KeySelectionManager getKeySelectionManager()

Example

In the following code shows how to use JComboBox.getKeySelectionManager() method.

/* w  w w.j  a  va  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);

    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) {
      int ix = ksm.selectionForKey(ch, cb.getModel());
      boolean noMatch = ix < 0;
      boolean uniqueItem = ix == curIx;

      if (noMatch || !uniqueItem) {
        cb.showPopup();
      }
    }
  }
}