01: /*
02: * Copyright 2001-2007 Geert Bevin <gbevin[remove] at uwyn dot com>
03: * Distributed under the terms of either:
04: * - the common development and distribution license (CDDL), v1.0; or
05: * - the GNU Lesser General Public License, v2.1 or later
06: * $Id: JKeySelectableList.java 3634 2007-01-08 21:42:24Z gbevin $
07: */
08: package com.uwyn.rife.swing;
09:
10: import java.awt.event.KeyEvent;
11: import java.awt.event.KeyListener;
12: import java.util.Vector;
13: import javax.swing.JList;
14: import javax.swing.ListModel;
15:
16: public class JKeySelectableList extends JList implements KeyListener {
17: private static final long serialVersionUID = -9040186688203231054L;
18:
19: public JKeySelectableList() {
20: super ();
21: addKeyListener(this );
22: }
23:
24: public JKeySelectableList(Vector items) {
25: super (items);
26: addKeyListener(this );
27: }
28:
29: public void keyReleased(KeyEvent event) {
30: }
31:
32: public void keyPressed(KeyEvent event) {
33: }
34:
35: public void keyTyped(KeyEvent event) {
36: selectWithKeyChar(event.getKeyChar());
37: }
38:
39: public boolean selectWithKeyChar(char keyChar) {
40: int index = -1;
41:
42: index = selectionForKey(keyChar, getModel());
43:
44: if (-1 != index) {
45: setSelectedIndex(index);
46: ensureIndexIsVisible(index);
47:
48: return true;
49: } else {
50: return false;
51: }
52: }
53:
54: public int selectionForKey(char key, ListModel listModel) {
55: int i = 0;
56: int size = 0;
57: int current_selection = -1;
58:
59: Object selected_item = listModel
60: .getElementAt(getSelectedIndex());
61: String value = null;
62: String pattern = null;
63:
64: size = listModel.getSize();
65:
66: if (null != selected_item) {
67: selected_item = selected_item.toString();
68:
69: for (i = 0; i < size; i++) {
70: if (selected_item.equals(listModel.getElementAt(i)
71: .toString())) {
72: current_selection = i;
73: break;
74: }
75: }
76: }
77:
78: pattern = ("" + key).toLowerCase();
79: key = pattern.charAt(0);
80:
81: for (i = ++current_selection; i < size; i++) {
82: value = listModel.getElementAt(i).toString().toLowerCase();
83: if (value.length() > 0 && key == value.charAt(0)) {
84: return i;
85: }
86: }
87:
88: for (i = 0; i < current_selection; i++) {
89: value = listModel.getElementAt(i).toString().toLowerCase();
90: if (value.length() > 0 && key == value.charAt(0)) {
91: return i;
92: }
93: }
94:
95: return -1;
96: }
97: }
|