swing - java comboBox autocomplete -
can tell me how change code have autoselection , able write not existing items, because doesnt let me write new items.
public class comboboxfill extends plaindocument { comboboxmodel model; jcombobox combobox=new jcombobox(); jtextcomponent editor; public comboboxfill(comboboxmodel model, jcombobox combobox,jtextcomponent editor) { this.model = model; this.combobox=combobox; this.editor=editor; } public void insertstring (int offs,string str,attributeset a) throws badlocationexception { string currenttext=gettext(0,getlength()); string beforeoffset=currenttext.substring(0,offs); string afteroffset=currenttext.substring(offs,currenttext.length()); string futuretext = beforeoffset+str+afteroffset; object item =lookupitem(futuretext); if (item!=null) { combobox.setselecteditem(item); }else { item = combobox.getselecteditem(); offs=offs-str.length(); combobox.gettoolkit().beep(); } super.remove(0, getlength()); super.insertstring(0, item.tostring(), a); if (item.tostring().equals(str)&&offs==0) { highlightcompletedtext(0); }else{ highlightcompletedtext(offs+str.length()); combobox.setpopupvisible(true); } } private boolean startswithignorecase(string str1, string str2) { return str1.touppercase().startswith(str2.touppercase()); } private void highlightcompletedtext(int start) { editor.setcaretposition (getlength()); editor.movecaretposition(start); } private object lookupitem(string pattern) { object selecteditem=model.getselecteditem(); if (selecteditem!=null && startswithignorecase(selecteditem.tostring(), pattern)){ return selecteditem; }else{ (int i=0, n=model.getsize();i<n;i++){ object currentitem = model.getelementat(i); if (startswithignorecase(currentitem.tostring(),pattern)) { return currentitem; } } } return null; }
}
i call way:
jtextcomponent editor3 = (jtextcomponent) combobox_2.geteditor().geteditorcomponent(); editor3.setdocument(new comboboxfill(combobox_2.getmodel(),combobox_2, editor3));
java2s has example this: autocompletecombobox
Comments
Post a Comment