简体   繁体   English

如何使用setSelectedValue在JList中设置多个项目?

[英]How to set multiple items as selected in JList using setSelectedValue?

I have a jList that is populated dynamically by adding to the underlying listModel. 我有一个通过添加到底层listModel动态填充的jList。 Now if I have three Strings whose value I know and I do 现在,如果我有三个字符串我知道并且我知道它的价值

for(i=0;i<3;i++){
    jList.setSelectedValue(obj[i],true);//true is for shouldScroll or not
}

only the last item appears to be selected...If this can't be done and I have to set the selection from the underlying model how should I go about it??? 只有最后一项似乎被选中...如果这不能做,我必须从基础模型中设置选择我该如何去做?

Also please note the jList has selection mode: 另请注意jList有选择模式:

  jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

Thanks in Advance 提前致谢

Note that all xxSelectedValue methods are convenience wrapper methods around the selectionModel (which supports index-based selection access only) on the JList. 请注意,所有xxSelectedValue方法都是在JList上围绕selectionModel(仅支持基于索引的选择访问)的便捷包装方法。 Setting multiple selections per value is not supported. 不支持为每个值设置多个选择。 If you really want it, you'll have to implement a convenience method yourself. 如果你真的想要它,你必须自己实现一个方便的方法。 Basically, you'll have to loop over the model's elements until you find the corresponding indices and call the index-based methods, something like: 基本上,你必须遍历模型的元素,直到找到相应的索引并调用基于索引的方法,如:

public void setSelectedValues(JList list, Object... values) {
    list.clearSelection();
    for (Object value : values) {
        int index = getIndex(list.getModel(), value);
        if (index >=0) {
            list.addSelectionInterval(index, index);
        }
    }
    list.ensureIndexIsVisible(list.getSelectedIndex());
}

public int getIndex(ListModel model, Object value) {
    if (value == null) return -1;
    if (model instanceof DefaultListModel) {
        return ((DefaultListModel) model).indexOf(value);
    }
    for (int i = 0; i < model.getSize(); i++) {
        if (value.equals(model.getElementAt(i))) return i;
    }
    return -1;
}
jList.addSelectionInterval(0,2);

Although StanislasV answer is perfectly valid, i would prefer to avoid adding one selection interval to another. 尽管StanislasV的答案完全有效,但我宁愿避免将一个选择间隔添加到另一个。 Instead, you should prefer to call the JList associated ListSelectionModel#setSelectionInterval(int, int) method like this : 相反,您应该更喜欢调用JList关联的ListSelectionModel#setSelectionInterval(int, int)方法,如下所示:

jList.getSelectionModel().setSelectionInterval(0, 3)

If you want your list selection to be disjoint, you'll moreover have to write your own ListSelectionModel . 如果您希望列表选择不相交,那么您还必须编写自己的ListSelectionModel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM