开发者

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

开发者 https://www.devze.com 2023-03-05 05:35 出处:网络
I have a jList that is populated dynamically by adding to the underlying listModel. Now if I have three Strings whose value I know and I do

I have a jList that is populated dynamically by adding to the underlying listModel. Now if I have three Strings whose value I know and I do

for(i=0;i<3;i++){
    jList.setSelectedValue(ob开发者_JS百科j[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.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. 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. Instead, you should prefer to call the JList associated ListSelectionModel#setSelectionInterval(int, int) method like this :

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

If you want your list selection to be disjoint, you'll moreover have to write your own ListSelectionModel.

0

精彩评论

暂无评论...
验证码 换一张
取 消