Select an Item in a JComboBox with Multiple Keystrokes in Java
Description
The following code shows how to select an Item in a JComboBox with Multiple Keystrokes.
Example
//from w ww .java 2 s . c o m
import java.awt.BorderLayout;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
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());
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout(10, 10));
panel.add(cb, BorderLayout.CENTER);
JFrame f = new JFrame();
f.add(panel);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
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;
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »