问题描述
我需要我的组合框有短名称的组织。问题是我可以在下拉列表中查看单位名称,但不能实际选择它。我的错误在哪里?
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();
}
}
设置型号:
query =session.createQuery("from Organization where isMain = 0");
List orgs=query.list();
toComboBox.setModel(new ToComboBoxModel(orgs));
提前感谢!
推荐答案
我怀疑你的 setSelectedItem()
方法使用 ==
.equals()
I suspect it's that your setSelectedItem()
method compares objects using ==
rather than .equals()
请考虑使用已经实现了有用的方法。
Consider using a DefaultComboBoxModel which already implements useful methods.
Edit :
此外,根据文档,当调用setSelected时,您应该调用所有注册的 ListDataListener
对象。
使用 DefaultComboBoxModel
是相当简单的。您创建一个新的 DefaultComboBoxModel
添加您要包含的元素,然后调用 getSelectedItem()
目前已选择。
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.
这篇关于Java swing:实现我的Comboboxmodel for JComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!