【问题标题】:Remove All Elements from a GridY zone从 GridY 区域中删除所有元素
【发布时间】:2019-08-06 21:11:14
【问题描述】:

我正在尝试创建一个设置 JLabels 的程序,使用 GridBagLayout。

我想创建一个按钮,按下该按钮会从某个 gridY 位置删除所有内容。我该怎么做呢。谢谢。

【问题讨论】:

    标签: java eclipse swing


    【解决方案1】:

    简单。当您将这些组件添加到它们的父容器时,请将它们保存在一个结构中(可能是一个列表)。比如:

        JPanel container = new JPanel(new GridBagLayout());
        //...
        List<Component> components = new ArrayList<>();
        // Add components to container and to list...
        for (Component c : components) {
            container.remove(c);
        }
        container.revalidate();
        container.repaint();
    

    【讨论】:

      【解决方案2】:
      1. Container 类有一个方法getLayout()。这将允许您为您的面板获取 GridBagLayout 实例。
      2. Container 类也有一个方法getComponents()

      因此,一旦您获得了数组中的所有组件,您就可以遍历该数组。对于每个组件,您会:

      1. 使用GridBagLayoutgetConstraints() 方法。
      2. 然后检查GridBagConstraints对象的gridy值,看看组件在哪一行。
      3. 如果组件符合您的条件,则从面板中删除它。

      循环结束后,您在面板上调用revalidate()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-01
        • 1970-01-01
        • 2014-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多