问题
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