2013-03-22 75 views
1

我使用此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 
+2

如果鍵集被鏈接到HashMap中,你可能得到一個ConcurrentModification例外。在這種情況下,只需複製集合並遍歷複製的集合。 – Paranaix 2013-03-22 15:10:57

回答

1

如果你想從HashMap中刪除,你需要在迭代器的幫助下刪除。
Calling remove in foreach loop in Java

編輯:按照OP ...

Iterator<String> it = names.iterator(); 
while(it.hasNext()) { 
    System.out.println(names); 
    String buttonName = it.next(); 
    JButton b = buttonCache.get(buttonName); 
    it.remove(); 
} 
System.out.println(names); 
+0

我剛剛嘗試過使用迭代器,結果相同。讓我再試一次,並用代碼確認。 – Juan 2013-03-22 15:28:58

+0

@Juan也嘗試評論visualUI.remove(b);線。我不確定這是什麼,但是這會告訴你,如果你的問題在那裏。也嘗試發佈你得到的例外。 – 2013-03-22 15:31:32

+0

好吧,我認爲只要稍微洗牌一下,我就能做到。如果需要,可以將此代碼添加到您的答案中:Iterator it = names.iterator(); (it.hasNext()){System.out.println(names); String buttonName = it.next(); JButton b = buttonCache.get(buttonName); it.remove(); } System.out.println(names); – Juan 2013-03-22 15:42:08

0

只是一個猜測。當你從Hashmap中移除按鈕時,它仍然可以在UI中找到,並且不再有任何參考。也許這是一個問題。我看到了一些註釋行,應該注意從snippit的UI中刪除按鈕 - 我想你應該讓他們這樣做,然後看看會發生什麼。