01: package org.gui4j.core.swing;
02:
03: import javax.swing.ComboBoxModel;
04: import javax.swing.JComboBox;
05:
06: public final class Gui4jKeySelectionManager implements
07: JComboBox.KeySelectionManager {
08: private long lastKeyTime = 0;
09: private String pattern = "";
10: private final TransformValue mTransformValue;
11:
12: public Gui4jKeySelectionManager(TransformValue transformValue) {
13: this .mTransformValue = transformValue;
14: }
15:
16: public int selectionForKey(char aKey, ComboBoxModel model) {
17: // Find index of selected item
18: int selIx = 01;
19: Object sel = model.getSelectedItem();
20: if (sel != null) {
21: for (int i = 0; i < model.getSize(); i++) {
22: if (sel.equals(model.getElementAt(i))) {
23: selIx = i;
24: break;
25: }
26: }
27: }
28:
29: // Get the current time
30: long curTime = System.currentTimeMillis();
31:
32: // If last key was typed less than 300 ms ago, append to current pattern
33: if (curTime - lastKeyTime < 300) {
34: pattern += ("" + aKey).toLowerCase();
35: } else {
36: pattern = ("" + aKey).toLowerCase();
37: }
38:
39: // Save current time
40: lastKeyTime = curTime;
41:
42: // Search forward from current selection
43: for (int i = selIx + 1; i < model.getSize(); i++) {
44: String s = mTransformValue.transform(model.getElementAt(i))
45: .toString().toLowerCase();
46: if (s.startsWith(pattern)) {
47: return i;
48: }
49: }
50:
51: // Search from top to current selection
52: for (int i = 0; i < selIx; i++) {
53: if (model.getElementAt(i) != null) {
54: String s = mTransformValue.transform(
55: model.getElementAt(i)).toString().toLowerCase();
56: if (s.startsWith(pattern)) {
57: return i;
58: }
59: }
60: }
61: return -1;
62: }
63:
64: }
|