【问题标题】:Deleting all buttons dynamically动态删除所有按钮
【发布时间】:2013-03-12 12:07:59
【问题描述】:

我使用这个answer 将按钮动态添加到我的 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

【问题讨论】:

  • 如果键集链接到 HashMap,您可能会收到 ConcurrentModification 异常。在这种情况下,只需复制集合并遍历复制的集合。

标签: java swing


【解决方案1】:

只是猜测。当您从 Hashmap 中删除按钮时,它可能仍会在 UI 中找到并且不再有任何引用。也许那是一个问题。我看到注释行应该注意从您的代码片段中的 UI 中删除按钮 - 我想您应该让他们这样做,然后看看会发生什么。

【讨论】:

    【解决方案2】:

    如果你想从 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);
    

    【讨论】:

    • 我刚刚尝试了一个迭代器并得到了相同的结果。让我再试一次,并用代码确认。
    • @Juan 也尝试注释掉 visualUI.remove(b);线。我不确定这是做什么的,但这会告诉你你的问题是否存在。也尝试发布你得到的异常。
    • 好吧,我想只要稍微调整一下,我就可以做到。如果需要,您可以将此代码添加到您的答案中: Iterator it = names.iterator(); while(it.hasNext()) { System.out.println(names);字符串按钮名称 = it.next(); JButton b = buttonCache.get(buttonName); it.remove(); } System.out.println(names);
    猜你喜欢
    • 2016-07-15
    • 2019-05-02
    • 1970-01-01
    • 2017-06-23
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    • 2019-12-21
    相关资源
    最近更新 更多