Re: How to update JComboBox without Selected Item being changed
wesley.hall@gmail.com schrieb:
You could remove the listeners before updating the ComboBox, then restore them
after the update is complete:
In any case, I dont think it will solve the OPs problem. Calling
'removeAllItems' will result in the selected item being lost.
I know this issue, I restore the selected item after updating the
contents.
setup_cbport.setSelectedItem(port); // previously selected item
After all, the modification of the combobox is not a bad idea.
Vector<String> set=new Vector<String>();
while (...) {
// collect items from the OS
set.add(pId.getName());
}
// delete items from the box
Vector<String> set2=new Vector<String>();
int i=0; while (i<setup_cbport.getItemCount()) {
String itm=(String)setup_cbport.getItemAt(i);
if (!set.contains(itm)) setup_cbport.removeItemAt(i);
else {set2.add(itm); i++;}
}
// add new items
Iterator it = set.iterator();
while (it.hasNext()) {
Object itm=it.next();
if (!set2.contains(itm)) setup_cbport.addItem(itm);
}