[英]Removing an item from a JList
我知道以前曾問過這個問題,並且有很多線程可以剪切和粘貼工作代碼,但是我的問題是為什么下面的代碼無法正常工作。 我試圖從JList中刪除多個項目,但是當我運行以下代碼時,出現了超出范圍的異常。 這是代碼段:
static DefaultListModel<File> listModel = new DefaultListModel<>();
JList<File> fileList = new JList<>(listModel);
void removeFiles() {
int[] listRange = new int[100];
listRange = fileList.getSelectedIndices();
int i = 0;
while (i <= listRange.length) {
listModel.remove(listRange[i]);
i++;
}
}
我已經使用調試語句來確認fileList
正在獲取數據(即,如果我添加4個文件,其長度為4),並且我還確認了listRange
的索引代表了我要刪除的文件的索引。 但是由於某種原因,它不會刪除它們。 我嘗試從fileList
以及模型( listModel
)中listModel
,但是都listModel
正常工作。 我在這里俯瞰什么嗎? 謝謝。
當您從列表中刪除一個項目時,其大小將減小。
因此,例如,在3個項目的列表中,您要刪除索引1和2的項目。刪除第一個項目時,列表中只有2個項目保留在索引0和1。所以調用list.remove(2)
將導致outOfBoundException
一種可能的解決方案是使用迭代器並繼續調用下一個,直到達到要刪除的索引之一,然后對其調用remove。 或者只是將下一個要刪除的索引減少已執行的刪除次數
PS:僅當getSelectedIndices
返回有序數組時,此方法才有效。 否則,您必須自己訂購索引
static DefaultListModel<File> listModel = new DefaultListModel<>();
JList<File> fileList = new JList<>(listModel);
void removeFiles() {
int[] listRange = new int[100];
listRange = fileList.getSelectedIndices();
int i = 0;
//The counter of the removed items so far
int nbOfRemovedItems = 0;
while (i <= listRange.length) {
// After each remove, the index of the items is decreased by one
listModel.remove(listRange[i] - nbOfRemovedItems);
++nbOfRemovedItems;
i++;
}
}
開箱即用的解決方案是按照相反的順序刪除項目,以避免出現越界異常:
int[] listRange = fileList.getSelectedIndices();
int i = listRange.length-1;
while (i >= 0) {
listModel.remove(listRange[i]);
i--;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.