如何通过值设置JComboBox的选定索引
- 论坛
- 如何通过值设置JComboBox的选定索引
6 浏览
如何通过值设置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", "橙子")); test.addItem(new ComboItem("1", "梨子")); test.addItem(new ComboItem("2", "苹果")); test.addItem(new ComboItem("3", "香蕉")); test.setSelectedItem("香蕉");
好的,我稍微修改了一下我的问题。我忘记了我的JComboBox中有一个自定义项,这使得问题稍微复杂一些。我不能使用setSelectedItem,因为每个项中都有一个ComboItem。那么,我该如何解决这个问题呢?