Adding a class instance to JComboBox [duplicate]

那年仲夏 提交于 2020-01-06 05:07:14

问题


In this question (Adding items to a JComboBox) it is described how an Item can be added to a JComboBox. This would allow to store an Object in a JComboBox, and overriding the toString() method the JComboBox would display a value and it will return the whole object.

I have included the following class:

public class ComboItem {

    private String key;
    private String value;

    public ComboItem(String key, String value)
    {
        this.key = key;
        this.value = value;
    }

    @Override
    public String toString()
    {
        return key;
    }

    public String getKey()
    {
        return key;
    }

    public String getValue()
    {
        return value;
    }
}

And then I try to add this to my JComboBox comboTimeZoneChart:

comboTimeZoneChart.addItem(new ComboItem("bar", "foo"));

But I get the following error in Netbeans:

incompatible types: ComboItem cannot be converted to String

I have double check but I do not know what could be wrong. This issue/problem is also reflected with 5 upvotes in the accepted answer of the original question included so it seems I am not the only one facing this issue.

I include an image of the error:


回答1:


comboTimeZoneChart.addItem(new ComboItem("bar","foo").toString());



来源:https://stackoverflow.com/questions/58789483/adding-a-class-instance-to-jcombobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!