How to set multiple items selected in JList using setSelectedValue?

I have a jList that populates dynamically, addingModel to the main list. Now, if I have three lines 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 element is displayed ... If this is not done, and I need to set the selection from the base model, how do I do this ???

Also note that jList has a select mode:

  jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); 

Thanks at Advance

+6
source share
3 answers

Despite the fact that StanislasV's answer is absolutely correct, I would prefer not to add one selection interval to another. Instead, you should select the JList related ListSelectionModel#setSelectionInterval(int, int) method similar to this:

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

If you want your list to be incompatible, you will also have to write your own ListSelectionModel .

-2
source

Note that all xxSelectedValue methods are convenience traversal methods around the selectionModel method (which only supports index-based access) in JList. Setting multiple parameters to the same value is not supported. If you really want this, you will have to implement the convenience method yourself. Basically, you will have to iterate over the model elements until you find the corresponding indexes and call the index-based methods, for example:

 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; } 
+10
source
 jList.addSelectionInterval(0,2); 
+3
source

Source: https://habr.com/ru/post/887799/


All Articles