JComboBox设置selectedItem不起作用

时间:2018-01-30 13:57:38

标签: java swing jcombobox

我正在用Java构建swing应用程序。 我有一个包含Items列表的JComboBox。 之后,我想设置这个JComboBox的选定项目,但我无法做到这一点。

这是我用来在JComboBox中添加Item的代码:

List<Stagione> listaStagioni = modelManager.getStagioneManager().getAllStagioni(null, null);
ComboFormat comboStagione = new ComboFormat();
comboStagione.setModel(new javax.swing.DefaultComboBoxModel(listaStagioni.toArray()));
comboStagione.addItem("");
comboStagione.setSelectedIndex(listaStagioni.size());

这是Stagione这个班:

public class Stagione {
    private Integer id;
    private Integer anno;
    private String descrizione;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getAnno() {
        return anno;
    }
    public void setAnno(Integer anno) {
        this.anno = anno;
    }
    public String getDescrizione() {
        return descrizione;
    }
    public void setDescrizione(String descrizione) {
        this.descrizione = descrizione;
    }

    public String toString() {
            return this.getDescrizione();
    }
}

在这段代码中,我想从代码中设置JComboBox中的Item

comboCategoria.setSelectedItem("MAGLIE");

我没有任何错误,但未选中该项。 这是我的JComboBox中的项目 enter image description here

3 个答案:

答案 0 :(得分:3)

setSelectedItem internaly使用equals方法。 您添加了Stagione对象,但在setSelectItem中使用了一个String。

在您的情况下,最简单的解决方案是在Stagion对象中重写equals以处理String比较。

喜欢:

 @Override
public boolean equals(Object obj) {
    if(obj==null){
        return false;
    }

    if(obj instanceof Stagione){
        return ((Stagione)obj).getId().equals(getId());
    }else if (obj instanceof String){
        return descrizione.equals(obj);
    }else {
        // Or return false...
        return super.equals(obj);
    }
}
PS:我不是使用实例的忠实粉丝。 Comaring String和Business Objects,好吧...... 从对象的角度来看,在setSelectedItem中使用Stagione对象会更干净,但无论如何你必须实现equals,例如通过ID进行比较。

答案 1 :(得分:1)

另一种常见的方法是设置索引而不是项目。 像这样的东西;

String testValue = "MAGLIE";

for (int i=0; i<combobox.getModel().getSize(); i++)
{
    if (combobox.getItemAt(i).toString().equals(testValue))
    {
        combobox.setSelectedIndex(i);
        break;
    }
}

答案 2 :(得分:0)

与您的问题没有直接关系,但以下情况不起作用:

comboStagione.setSelectedIndex(listaStagioni.size());

Java索引是0偏移量,因此要选择最后一项是您使用的列表:

comboStagione.setSelectedIndex(listaStagioni.size() - 1);