【问题标题】:Using Grix, gridy to remove JTextField使用 Grix、gridy 删除 JTextField
【发布时间】:2019-08-07 19:27:28
【问题描述】:

我想知道是否可以使用删除 JTextField GridBagLayout 并像这样删除。

PANEL.remove(gridx.5, gridy.5) ---

或者我怎样才能用这种逻辑删除。

【问题讨论】:

标签: java eclipse swing


【解决方案1】:

不,没有方法可以做到这一点,您需要自己编写。

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

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

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

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

编辑:

您需要在代码中的某处将布局管理器设置为 GridBagLayout。然后使用 GridBagConstraints 将组件添加到面板。

那么以后当你想从面板中移除组件时你需要参考:

  1. 您将组件添加到的 JPanel
  2. 上面面板的GridBagLayout

我为您提供了完成此任务所需的方法。那么,您是否阅读了我建议您需要使用的方法的 API?

基本代码是:

GridBagLayout layout = (GridBagLayout)panel;
Component[] components = panel.getComponent();

for (each component in the array)
{
    GridBagConstraint gbc = layout.getConstraints( component )

    if (gbc.gridX == ?? && gbc.gridY = ??)
    {
        // remove the component from the panel
    }
}

panel.revalidate();

所以我建议你创建一个方法来传递你想要查找的组件的行和列。然后你可以改变 if 条件来访问这些参数。

【讨论】:

  • createInPanel.getLayout(); List components = new ArrayList(); components.addAll(createInPanel.getComponents());
  • 其中 createInPanel 是作为 gridbaglayout 的面板。我认为我没有正确理解这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多