How to remove multiple items in JList

时光毁灭记忆、已成空白 提交于 2019-12-10 17:30:02

问题


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

Help please

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


回答1:


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



回答2:


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.




回答3:


My solution:

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

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



回答4:


public int[] getSelectedIndices()



回答5:


where foo is the JList:

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


来源:https://stackoverflow.com/questions/7672260/how-to-remove-multiple-items-in-jlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!