【问题标题】:Replace Component in GridBagLayout替换 GridBagLayout 中的组件
【发布时间】:2013-02-22 03:34:46
【问题描述】:

我创建了一个从 JPanel 扩展的类,其布局属性是 GridBagLayout。我基本上需要显示一个 JLabels 数组(网格),但是一旦创建了组件,我就无法替换它。我尝试删除要更改的组件,然后放置新组件,但结果很奇怪。例如,我创建了一个 10x10 JLabels 数组,并希望用以下代码替换 position[0][0] 和 position[9][9]:

//At first i have the jpanel layout completely filled

this.remove(0);
this.add((JLabel) start, 0);  //This was created with GridBagLayout.gridx = 0 and GridBagLayout.gridy = 0 and it's fine

this.remove(99);
this.add((JLabel) end, 99); //This was created with GridBagLayout.gridx = 9 and GridBagLayout.gridy = 9 and it's out of grid
this.revalidate();

但只有 position[0][0] 看起来不错。我应该怎么做才能更换组件?

【问题讨论】:

    标签: java swing awt jpanel layout-manager


    【解决方案1】:

    GridBagLayout 中,每个组件都与GridBagConstraints 相关联。简单地移除一个组件并用相同位置的组件替换它是行不通的,因为新组件将收到一个新的GridBagConstraints

    但是,您可以做的是获取与给定组件关联的约束。

    Component toRemove = getComponent(0);
    GridBagLayout layout = (GridBagLayout)getLayout();
    GridBagConstraints gbc = layout.getConstraints();
    remove(toRemove);
    add(new JLabel("Happy"), gbc, 0);
    

    这将使用与您要删除的组件相同的约束来添加组件。

    这当然都假设您正在分配 gridx/gridy 约束...

    【讨论】:

    • @System.exit:还要考虑更新组件。
    • 我试过你的代码,但结果完全一样,谢谢!
    • @MadProgrammer 我确实使用 gridx / gridy
    【解决方案2】:

    我通过以下方式解决了我的问题:

    this.setComponentZOrder(newItem, 0);
    

    所以,我实际上并没有删除 Jpanel 上的对象,而是将新对象放在旧对象上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2022-01-12
      相关资源
      最近更新 更多