VextoR
VextoR

Reputation: 5175

How to remove multiple items in JList

It's funny, I can't find out how to delete multiple selected items in a JList

Help please

enter image description here

UPD: OK, the problem was in NetBeans, because it creates JList and sets model AbstractListModel which somehow not working with remove method.

Upvotes: 5

Views: 9551

Answers (5)

Chris
Chris

Reputation: 727

I came across this problem too. All posted solutions did not work for me because if I call DefaultListModel#remove(int) it will modify the underlying list and thus the indices which I gathered before with JList#getSelectedIndices() are no longer valid.

I came to this solution, which worked for me.

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

By handling the selected Objects I don't have to care about indices and their validity.

Upvotes: 3

Kleon
Kleon

Reputation: 11

My solution:

DefaultListModel dlm = (DefaultListModel) lst.getModel();
int count = lst.getSelectedIndices().length;

for (int i = 0; i < count; i++)
{
     dlm.removeElementAt(lst.getSelectedIndex());
}

Upvotes: 1

VextoR
VextoR

Reputation: 5175

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

Upvotes: 17

Simiil
Simiil

Reputation: 2311

where foo is the JList:

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

Upvotes: -1

StanislavL
StanislavL

Reputation: 57421

public int[] getSelectedIndices()

Upvotes: 0

Related Questions