JList autocomplete with Vector
I'm working on an autocomplete JList of Vectors which suggests according to text entry in a JTextField. Thus, at any given point during text alteration i.e. during text entry as well as backspacing existing text, the JList should display only the items that contain the search string.
I tried the following code:
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;
public class MyList {
JTextField searchField = new JTextField();
MyList() {
JFrame myFrame = new JFrame();
Vector<String> listElements = new Vector<String>();
listElements.addElement("cccc");
listElements.addElement("abab");
listElements.addElement("baba");
listElements.addElement("babb");
final JList list = new JList(listElements);
final JScrollPane spane = new JScrollPane(list);
myFrame.setLayout(new GridLayout(1,1));
myFrame.add(searchField);
searchField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent keyEvent) {
String searchText = searchField.getText();
Vector<String> newListElements = new Vector<String>();
for(int i = 0; i < list.getModel().getSize(); i++) {
String listElement = list.getModel().getElementAt(i).toString();
if(listElement.toLowerCase().contains(searchText.toLowerCase())) {
newListElements.add(i, listElement);
}
}
list.setListData(newListElements);
}
});
myFrame.add(spane);
myFrame.setSize(300, 300);
myFrame.setVisible(true);
}
public static void main(String args[]) {
MyList list = new MyList();
}
}
I'm experiencing different runtime problems at different stages, so rather than asking multiple questions, I request you to examine the above code, point out any discrepancies therein and suggest possible improvements. Thanks a lot.