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

Niranjani S picture Niranjani S · May 11, 2011 · Viewed 15.5k times · Source

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(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.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

Thanks in Advance

Answer

kleopatra picture kleopatra · May 11, 2011

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;
}