将类实例添加到JComboBox [英] Adding a class instance to JComboBox

查看:122
本文介绍了将类实例添加到JComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此问题中(将项目添加到JComboBox ),它描述了如何可以将项目添加到JComboBox. 这样可以将一个对象存储在JComboBox中,并覆盖toString()方法,JComboBox将显示一个值,它将返回整个对象.

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.

我包括以下课程:

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;
    }
}

然后我尝试将其添加到我的JComboBox comboTimeZoneChart:

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

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

但是我在Netbeans中遇到以下错误:

But I get the following error in Netbeans:

incompatible types: ComboItem cannot be converted to String

我已经仔细检查过,但我不知道这可能是错的. 这个问题/问题在原始问题的公认答案中也得到5反映,所以我似乎并不是唯一面对这个问题的人.

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.

我附有错误图片:

推荐答案

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

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

这篇关于将类实例添加到JComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆