如何按值设置选定的索引JComboBox [英] How to set selected index JComboBox by value

查看:560
本文介绍了如何按值设置选定的索引JComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过值而不是索引在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:


  1. 遍历这些项目以找到一个(或者具有给定标签的那个的索引,然后调用 setSelectedItem(theFoundItem)(或 setSelectedIndex(theFoundIndex)

  2. 中覆盖等于 hashCode ComboItem 以便两个具有相同名称的 ComboItem 实例相等,只需使用 setSelectedItem(new ComboItem(anyNumber,)香蕉));

  1. Iterate through the items to find the one (or the index of the one) which has the given label, and then call setSelectedItem(theFoundItem) (or setSelectedIndex(theFoundIndex))
  2. Override equals and hashCode in ComboItem so that two ComboItem instances having the same name are equal, and simply use setSelectedItem(new ComboItem(anyNumber, "banana"));

这篇关于如何按值设置选定的索引JComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆