我使用此answer來動態地向我的GUI添加按鈕,並期望能夠將它們全部刪除。據我的理解,我得到了HashMap(字符串)中的所有鍵,然後我對鍵進行for循環,並從hashmap中刪除它們(讓對象返回,我將刪除它)。問題是,從hashmap中刪除第一個按鈕後,循環不會繼續,我的應用程序崩潰。動態刪除所有按鈕
HashMap<String, JButton> buttonCache = new HashMap<>();
Set<String> names = buttonCache.keySet();
/*
* Checking which buttons exist in the hashmap
*/
for (String name0 : names) {
System.out.println("Name0: " + name0);
}
for (String name1 : names) {
System.out.println("before removing: " + name1);
buttonCache.containsKey(name1); //making sure its in it.
JButton b = buttonCache.remove(name1);
System.out.println("after removing: " + name1);
//visualUI.remove(b); //not tested yet
}
//visualUI.invalidate(); //not tested yet
//visualUI.repaint(); //not tested yet
輸出是:
Name0: Cancel
Name0: Continue
2
before removing: Cancel
true
after removing: Cancel
如果鍵集被鏈接到HashMap中,你可能得到一個ConcurrentModification例外。在這種情況下,只需複製集合並遍歷複製的集合。 – Paranaix 2013-03-22 15:10:57