Selecting Items in a Choice Box by typing a key
I have a drop down choice box that has a list of book titles in it. I want to be able to type in a key in the choice box and have it 'jump down' to select the item that begins with that letter. I have added a keylistener but only does one key at a time. It also seems it looks for exact matches, and not substrings. I would also like it to be able to get a series of key's in a row. For example if I typed Z-O I would like it to go to Zebra first then zoo.
any suggestions?
public void chcIssueKeyTyped(java.awt.event.KeyEvent keyEvent) {
char c =keyEvent.getKeyChar();
String s =new String('c');
for (int i=0; i<getchcIssue().countItems();i++)
{
if (getchcIssue().getItem(i).startsWith(s)){
getchcIssue().select(i);
}//end if
}//end for
}//end chcIssueKeyTyped>
[854 byte] By [
jkirkpat] at [2007-9-26 7:05:31]

Use a StringBuffer to hold the sequence of keys, and use generic listeners that you can attach to any List component. To "jump to" an item, call makeVisible rather than select.
I suspect a "contains" search would drive users absolutely crazy. Imagine typing 'a' and having a list scroll down to "Zimbabwe"! Nevertheless, you could do it by replacing "startsWith(s)" with "indexOf(s) != -1" in the code below.
StringBuffer searchBuf = new StringBuffer();
KeyListener searchPositioner = new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == e.VK_ESCAPE) {
// clear the search string
searchBuf.setLength(0);
}
else {
searchBuf.append(e.getKeyChar());
String s = searchBuf.toString();
List list = (List) e.getSource();
for (int i = 0; i < list.countItems(); i++) {
// scroll to first item that starts with s
if (list.getItem(i).startsWith(s)){
// item starts with s, make it visible
list.makeVisible(i);
break;
}
}
}
}
};
FocusListener searchEraser = new FocusAdapter() {
public void focusLost(FocusEvent e) {
// clear the search string
searchBuf.setLength(0);
}
};
titleList.addKeyListener(searchPositioner);
titleList.addFocusListener(searchEraser);
authorList.addKeyListener(searchPositioner);
authorList.addFocusListener(searchEraser);
libraryList.addKeyListener(searchPositioner);
libraryList.addFocusListener(searchEraser);