Source Code : Selecting an Item in a JComboBox Component with Multiple Keystrokes

Java Is Open Source Programming Language You Can Download From Java and Java Libraries From http://www.oracle.com. Click Here to download
We provide this code related to title for you to solve your developing problem easily. Libraries which is import in this program you can download from http://www.oracle.com. Click Here or search from google with Libraries Name you get jar file related it

Selecting an Item in a JComboBox Component with Multiple Keystrokes

  

import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;

public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "A", "B", "B", "C", "C" };
    JComboBox cb = new JComboBox(items);
    cb.setKeySelectionManager(new MyKeySelectionManager());
  }
}

class MyKeySelectionManager implements JComboBox.KeySelectionManager {
  long lastKeyTime = 0;
  String pattern = "";

  public int selectionForKey(char aKey, ComboBoxModel model) {
    int selIx = 01;
    Object sel = model.getSelectedItem();
    if (sel != null) {
      for (int i = 0; i < model.getSize(); i++) {
        if (sel.equals(model.getElementAt(i))) {
          selIx = i;
          break;
        }
      }
    }
    long curTime = System.currentTimeMillis();
    if (curTime - lastKeyTime < 300) {
      pattern += ("" + aKey).toLowerCase();
    } else {
      pattern = ("" + aKey).toLowerCase();
    }
    lastKeyTime = curTime;
    for (int i = selIx + 1; i < model.getSize(); i++) {
      String s = model.getElementAt(i).toString().toLowerCase();
      if (s.startsWith(pattern)) {
        return i;
      }
    }
    for (int i = 0; i < selIx; i++) {
      if (model.getElementAt(i) != null) {
        String s = model.getElementAt(i).toString().toLowerCase();
        if (s.startsWith(pattern)) {
          return i;
        }
      }
    }
    return -1;
  }
}

   
    
  

Thank with us