I use a combo box on panel and as I know we can add items with the text only
comboBox.addItem(\'item text\');
But some times I need to
addItem(Object) takes an object. The default JComboBox renderer calls toString() on that object and that's what it shows as the label.
So, don't pass in a String to addItem(). Pass in an object whose toString() method returns the label you want. The object can contain any number of other data fields also.
Try passing this into your combobox and see how it renders. getSelectedItem() will return the object, which you can cast back to Widget to get the value from.
public final class Widget {
private final int value;
private final String label;
public Widget(int value, String label) {
this.value = value;
this.label = label;
}
public int getValue() {
return this.value;
}
public String toString() {
return this.label;
}
}