问题
I need my combo box to have short names of organizations. The problem is i can see organizations names in dropdown list, but cant actually select it. Where is my mistake?
public class ToComboBoxModel extends AbstractListModel implements ComboBoxModel {
private String selectedItem;
private List<Organization> orgs;
public ToComboBoxModel(List orgs) {
this.orgs = orgs;
}
@Override
public String getSelectedItem() {
return selectedItem;
}
@Override
public void setSelectedItem(Object newValue) {
for (Organization o: orgs){
if (newValue==o){
selectedItem=o.getShortName();
break;
}
}
}
@Override
public int getSize() {
return orgs.size();
}
@Override
public String getElementAt(int i) {
return orgs.get(i).getShortName();
}
}
Setting model:
query =session.createQuery("from Organization where isMain = 0");
List orgs=query.list();
toComboBox.setModel(new ToComboBoxModel(orgs));
Thanks in advance!
回答1:
I suspect it's that your setSelectedItem() method compares objects using == rather than .equals()
Consider using a DefaultComboBoxModel which already implements useful methods.
Edit:
Also according to the Docs you should be calling all registered ListDataListener objects when setSelected is called.
Using a DefaultComboBoxModel is fairly straightforward. You create a new DefaultComboBoxModel add the elements you want it to contain then call getSelectedItem() to retrieve the element that is currently selected.
来源:https://stackoverflow.com/questions/8254940/java-swing-implementing-my-comboboxmodel-for-jcombobox