动态删除所有按钮 [英] Deleting all buttons dynamically

查看:30
本文介绍了动态删除所有按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个 answer 将按钮动态添加到我的 GUI 中,并希望能够将它们全部删除.据我所知,我正在获取 HashMap(字符串)中的所有键,然后我对键进行 for 循环,并从哈希图中删除它们(取回我将删除的对象).问题是从哈希图中删除第一个按钮后,循环不会继续并且我的应用程序崩溃.

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

输出为:

Name0: Cancel
Name0: Continue
2
before removing: Cancel
true
after removing: Cancel

推荐答案

如果要从 HashMap 中删除,则需要借助迭代器进行删除.
请参阅在 Java 中的 foreach 循环中调用 remove.

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.

根据 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);

这篇关于动态删除所有按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆