Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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

like image 768
Niranjani S Avatar asked May 11 '11 08:05

Niranjani S


People also ask

How do I select multiple items in JList?

Multiple selection list enables the user to select many items from a JList. A SINGLE_INTERVAL_SELECTION list allows selection of a contiguous range of items in the list by clicking the first item, then holding the Shift key while clicking the last item to select in the range.

How do you select multiple values in Java?

In some cases, you need to allow your users to select multiple values rather than just one value from a list of choices. You can do this using one of the following component tags: An h:selectManyCheckbox tag, displayed as a set of check boxes. An h:selectManyMenu tag, displayed as a drop-down menu.

How do I add an item to a JList?

However, JList has no method to add or delete items once it is initialized. Instead, if you need to do this, you must use the ListModel class with a JList. Think of the ListModel as the object which holds the items and the JList as the displayer.


1 Answers

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;
}
like image 65
kleopatra Avatar answered Sep 22 '22 10:09

kleopatra