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 (and not necessarily just starting with the search string).

I tried out the following code:

Vector<String> listElements = new Vector<String>();
listElements.addElement("aaaa");
listElements.addElement("abab");
listElements.addElement("baba");
listElements.addElement("caba");	
final JList list = new JList(listElements);
final JTextField searchField = new JTextField("Type filter text");									
searchField.addKeyListener(new KeyAdapter() {
	public void keyPressed(KeyEvent keyEvent) {
    	Vector<String> newListElements = new Vector<String>();        		
	    for(int i = 0; i < list.getModel().getSize(); i++) {
        	String listElement = list.getModel().getElementAt(i).toString);        			        			        			        			
	        if(listElement.contains(searchField.getText())) {
            	newListElements.add(i, listElement);            			            			            			
            }	            				
        }	            		
        list.setListData(newListElements);        		       				
    }
});

On execution, it gives unpredictale results. For some instances it works OK and some times it doesn't.
Is there anything inherently wrong with the above code? Thanks.