JComboBox 同一个条目多次

JComboBox same entry multiple times

我有一个 JComboBox,我正在向其传递一个字符串数组。某些值在该数组中多次出现。组合框呈现正确,但我无法 select 所有条目。

String[] entrys = {"A", "B", "C", "A"};
JComboBox combo = new JComboBox(entrys);

在这个例子中,我将无法 select 第二个 A 因为数组前面已经有一个 A

combo.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED)
            System.out.println(combo.getSelectedIndex());
    }
});

如果我按第二个 A 它仍然是 select 第一个并打印 0

所以,基本上,JComboBox 是在 getSelectedIndex 方法中这样做的...

public int getSelectedIndex() {
    Object sObject = dataModel.getSelectedItem();
    int i,c;
    E obj;

    for ( i=0,c=dataModel.getSize();i<c;i++ ) {
        obj = dataModel.getElementAt(i);
        if ( obj != null && obj.equals(sObject) )
            return i;
    }
    return -1;

这就是为什么当您 select A 时,它会返回 0,因为它会在位置 0 找到与 selected 值匹配的对象].您需要围绕这些值生成一个唯一的对象包装器,这将允许与 select 正确值

进行比较

也许像...

public class Wrapper {
    private final String value;

    public Wrapper(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    // I personally prefer to use a custom cell renderer, but 
    // for the sake of brevity, I'm using the toString method instead
    @Override
    public String toString() {
        return value;
    }

}

然后我们需要映射 String 值...

String[] entrys = {"A", "B", "C", "A"};
Wrapper[] wrappers = Arrays.stream(entrys).map((String t) -> new Wrapper(t)).toArray(Wrapper[]::new);
JComboBox<Wrapper> b = new JComboBox<>(wrappers);

我们都准备好了。请记住,当您使用 getSelectedItem 时,您处理的是 Wrapper class,而不是 String,因此您需要解包它们