我使用这个答案动态地将按钮添加到我的 GUI 中,并希望能够删除所有这些按钮。据我了解,我正在获取 HashMap(字符串)中的所有键,然后我对键进行 for 循环,并从 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