JComboBox 设置 selectedItem 不起作用

JComboBox set selectedItem not works

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

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

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());

这是 class 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 中的项目

setSelectedItem 内部使用 equals 方法。 您添加了 Stagione 对象,但在 setSelectItem 中使用了一个字符串。

针对您的情况,最简单的解决方案是覆盖 Stagion 对象中的 equals 以处理字符串比较。

喜欢:

 @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 :我不太喜欢使用 instanceof。 比较字符串和业务对象,嗯...... 从对象的角度来看,在 setSelectedItem 中使用 Stagione 对象会更清晰,但无论如何您都必须实现 equals,例如通过 ID 进行比较。

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

String testValue = "MAGLIE";

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

与您的问题没有直接关系,但以下内容无效:

comboStagione.setSelectedIndex(listaStagioni.size());

Java 索引是 0 偏移量,所以 select 最后一项是您使用的列表:

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