简体   繁体   中英

Remove all selected elements from JList?

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.

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

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