Java Swing:为 JComboBox 实现我的 Comboboxmodel [英] Java swing: implementing my Comboboxmodel for JComboBox
问题描述
我需要我的组合框来显示组织的简称.问题是我可以在下拉列表中看到组织名称,但不能实际选择它.我的错误在哪里?
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()
考虑使用 DefaultComboBoxModel 已经实现有用的方法.
Consider using a DefaultComboBoxModel which already implements useful methods.
编辑:此外,根据文档,您应该在调用 setSelected 时调用所有已注册的 ListDataListener
对象.
Edit:
Also according to the Docs you should be calling all registered ListDataListener
objects when setSelected is called.
使用 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:为 JComboBox 实现我的 Comboboxmodel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!