Reputation: 35
I'm trying to remove the selected elements from a JList. I know how to remove one which is
((DefaultListModel) jList.getModel()).remove(index);
However; is there a way to remove my selected indices? I know of the function
list.getSelectedIndices();
Which returns an Int Array. I figured if I iterate through that to remove the indices it should work however I'm getting errors from that (Assuming because the indice # is going down.
Upvotes: 1
Views: 249
Reputation: 312219
Removing an element will "shift" all the elements that come after it, which is probably the cause of the errors you've been seeing. One way around this is to iterate over those indexes backwards, so you never handle the shifted part of the list:
DefaultListModel model = (DefaultListModel) jList.getModel();
int[] indexes = jList.getSelectedIndexes();
for (int i = indexes.length; i >= 0; --i) {
model.remove(indexes[i]);
}
Upvotes: 2