【发布时间】:2017-02-20 12:22:45
【问题描述】:
我搜索了如何在java中的jComboBox中放入额外的数据,我发现最多的结果是创建一个包含属性键和值的Item Class。
我已经这样做了,但是当我尝试使用 `new Item(key, value) 在 jComboBox 中添加项目时,我仍然遇到此错误,
错误代码是:
项目无法转换为字符串 jComboTemp1.addItem(new Item("CA", "Canada"));
这是类项目:
public class Item {
private int id;
private String description;
public Item(int id, String description) {
this.id = id;
this.description = description;
}
public int getId() {
return id;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return description;
}
}
虽然我已经覆盖了 toString 方法,但问题在这里显示:
jComboTemp1.addItem(new Item<String>("CA", "Canada"));
【问题讨论】:
-
发布一个真实的程序,minimal reproducible example 显示您的问题。您需要将 JComboBox 及其模型更改为
JComboBox<Item>和DefaultComboBoxModel<Item>类型。然后正确显示或者覆盖项目的toString(),或者给组合框一个渲染器。