简体   繁体   中英

Display more than one item as selected in a JList

I have a JList(with the option for Multiple Selections) and I need to display more than one Selected Item to the User:

This is what I tried:

myvaluesJlist is initialized with"a","b","c","d".

myvalues is an ArrayLsit of Strings containing values "a","c".

NOw I wasn the Jlist to display values in myValues to be selected.

When the dialog opens I want the for(String s : myvalues){ myvaluesJlist.setSelectedValue(s, true); } Where myvalues is the list of values that I need to display as selected,but in this case I can see only the "s" in the last Iteration as selected.

I tried to find a way to fetch the indices of the values present in myvalues, but with no Luck.Please help

I think this would do what you want

int[] select = new int[myValues.length];
int index = 0;
for(int i = 0; i < myvalues.length; i++){
   if(/*condition for selection here*/)
      select[index++] = i;
}
list.setSelectedIndices(Arrays.copyOf(select, index));

Note that if myvalues is a List then you can change the .length to .size()

In any case, you need to use setSelectedIndices to do what you want. Here a paste from the doc :

Changes the selection to be the set of indices specified by the given array. Indices greater than or equal to the model size are ignored. This is a convenience method that clears the selection and then uses addSelectionInterval on the selection model to add the indices. Refer to the documentation of the selection model class being used for details on how values less than 0 are handled.

http://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#setSelectedIndices(int[])

Found an answer here : http://www.wenda.io/questions/471727/how-to-set-multiple-items-as-selected-in-jlist-using-setselectedvalue.html

And it's working for me! Thanks to everyone anyway!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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