How to remove multiple items in JList

This is ridiculous, I canโ€™t find out how to remove multiple selected items in JList

help me please

enter image description here

UPD: Well, the problem was with NetBeans because it creates a JList and installs the AbstractListModel model, which somehow does not work with the remove method.

+4
source share
5 answers
  DefaultListModel dlm = (DefaultListModel) subjectList.getModel(); if(this.subjectList.getSelectedIndices().length > 0) { int[] selectedIndices = subjectList.getSelectedIndices(); for (int i = selectedIndices.length-1; i >=0; i--) { dlm.removeElementAt(selectedIndices[i]); } } 
+14
source

I also ran into this problem. All published solutions did not work for me, because if I call DefaultListModel # remove (int), it will change the base list and therefore the indexes that I collected earlier with JList # getSelectedIndices () are no longer valid.

I came to this solution that worked for me.

 for (MyObject o : jList1.getSelectedValuesList()) { ((DefaultListModel<MyObject>)jList1.getModel()).removeElement(o); } 

When processing selected objects, I donโ€™t need to worry about indexes and their validity.

+2
source

My decision:

 DefaultListModel dlm = (DefaultListModel) lst.getModel(); int count = lst.getSelectedIndices().length; for (int i = 0; i < count; i++) { dlm.removeElementAt(lst.getSelectedIndex()); } 
+1
source
 public int[] getSelectedIndices() 
0
source

where foo is a JList:

 int[] selected = foo.getSelectedIndices(); for(int i : selected){ foo.remove(i); } 
-1
source

All Articles