1

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
Community
  • 1
  • 1
Juan
  • 521
  • 1
  • 11
  • 28
  • 2
    If the keyset is linked to the HashMap you probably get a ConcurrentModification exception. In this case just copy the set and iterate over the copied set. – Sebastian Hoffmann Mar 22 '13 at 15:10

2 Answers2

1

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);
Community
  • 1
  • 1
Romain Hippeau
  • 24,113
  • 5
  • 60
  • 79
  • I did just tried with an iterator and had the same result. Let me try again, and confirm with the code. – Juan Mar 22 '13 at 15:28
  • @Juan also try commenting out the visualUI.remove(b); line. I am not sure what this does but that will tell you if your problem is in there. Also try posting the exception you get. – Romain Hippeau Mar 22 '13 at 15:31
  • Okay, I think that with a little shuffling I manage to do it. You can add this code to your answer if you want: Iterator 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); – Juan Mar 22 '13 at 15:42
0

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.

Phil
  • 200
  • 10