我用过这个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 中删除,你需要借助迭代器来删除。
请参阅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);
关于java - 动态删除所有按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15573661/