如何按值设置选定的索引 JComboBox
2022-09-01 09:11:07
我想在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。那么,我该如何完成这项工作呢?