如何按值设置选定的索引JComboBox [英] How to set selected index JComboBox by value
问题描述
我想通过值而不是索引在JComboBox中设置所选索引。怎么做?示例
I want to set the selected index in a JComboBox by the value not the index. How to do that? Example
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。那么,我怎么做呢?
Ok, I have modified my question a bit. I forgot that i have a custom item inside my JComboBox that makes it a bit more difficult. i cant do setSelectedItem as i have a ComboItem inside each item. So still, how do i get this done?
推荐答案
setSelectedItem(banana)
。您可以通过阅读 javadoc 。
编辑:因为你改变了问题,我会改变我的答案。
since you changed the question, I'll change my answer.
如果你想要选择具有香蕉标签的项目,那么你有两个解决方案:
If you want to select the item having the "banana" label, then you have two solutions:
- 遍历这些项目以找到一个(或者具有给定标签的那个的索引,然后调用
setSelectedItem(theFoundItem)
(或setSelectedIndex(theFoundIndex)
) - 在
中覆盖
以便两个具有相同名称的等于
和hashCode
ComboItemComboItem
实例相等,只需使用setSelectedItem(new ComboItem(anyNumber,)香蕉))
;
- Iterate through the items to find the one (or the index of the one) which has the given label, and then call
setSelectedItem(theFoundItem)
(orsetSelectedIndex(theFoundIndex)
) - Override
equals
andhashCode
inComboItem
so that twoComboItem
instances having the same name are equal, and simply usesetSelectedItem(new ComboItem(anyNumber, "banana"))
;
这篇关于如何按值设置选定的索引JComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!