Reputation: 532
I used this answer to add buttons to my GUI dynamically and expected to be able to remove all of them too. To my understanding I am getting all the keys in the HashMap (strings) and then I am doing a for loop over the keys, and deleting them from the hashmap (getting the object back which I will delete). Problem is that after deleting the first button from the hashmap, the loop doesn't continue and my application crashes.
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
The output is:
Name0: Cancel
Name0: Continue
2
before removing: Cancel
true
after removing: Cancel
Upvotes: 1
Views: 148
Reputation: 24375
If you want to delete from a HashMap you need to delete with the help of the iterator.
See Calling remove in foreach loop in Java.
EDIT: As per 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);
Upvotes: 1
Reputation: 320
Just a guess. When you remove the button from the Hashmap it maybe still be found in UI and doesn't have any reference anymore. Maybe thats one Problem. I see commented lines that should take care of removing the buttons from the UI in your snippit - I guess you should let them do that and see what happens then.
Upvotes: 0