我想通過值而不是索引在JComboBox中設置選定的索引。怎麼做?示例如何通過值設置選擇的索引JComboBox
public class ComboItem {
private String value;
private String label;
public ComboItem(String value, String label) {
this.value = value;
this.label = label;
}
public String getValue() {
return this.value;
}
public String getLabel() {
return this.label;
}
@Override
public String toString() {
return label;
}
}
JComboBox test = new JComboBox();
test.addItem(new ComboItem(0, "orange"));
test.addItem(new ComboItem(1, "pear"));
test.addItem(new ComboItem(2, "apple"));
test.addItem(new ComboItem(3, "banana"));
test.setSelectedItem("banana");
好吧,我修改了我的問題了一下。我忘記了我的JComboBox內有一個自定義項目,這使得它更加困難。我不能做setSelectedItem,因爲我在每個項目中都有一個ComboItem。那麼,我該如何做到這一點?
不使用包裝的物品。而是實現一個自定義的ListCellRenderer,它將組件映射到它的字符串表示 – kleopatra