【问题标题】:How to remove gaps in GridBagLayout?如何消除 GridBagLayout 中的空白?
【发布时间】:2023-03-15 04:49:01
【问题描述】:

我有一个 GridBagLayout JPanel,里面有一些组件,但是它们之间的空白太多了。

    float wx = 1f, wy = 1f;
    optionsPanel.add(optionsPanelLanguageSelectorInfo,
            new GridBagConstraints(0, 0, 1, 1, wx, wy,
                    GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                    new Insets(0, 100, 0, 10), 0, 0));
    optionsPanel.add(optionsPanelLanguageSelector,
            new GridBagConstraints(1, 0, 1, 1, wx, wy,
                    GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                    new Insets(0, 10, 0, 100), 0, 0));
    optionsPanel.add(optionsPanelAutoSaveToRecentSelectorInfo,
            new GridBagConstraints(0, 1, 1, 1, wx, wy,
                    GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                    new Insets(0, 100, 0, 10), 0, 0));
    optionsPanel.add(optionsPanelAutoSaveToRecentSelector,
            new GridBagConstraints(1, 1, 1, 1, wx, wy,
                    GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                    new Insets(0, 10, 0, 100), 0, 0));
    optionsPanel.add(optionsPanelAutoSecurityCheckSelectorInfo,
            new GridBagConstraints(0, 2, 1, 1, wx, wy,
                    GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                    new Insets(0, 100, 0, 10), 0, 0));
    optionsPanel.add(optionsPanelAutoSecurityCheckSelector,
            new GridBagConstraints(1, 2, 1, 1, wx, wy,
                    GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                    new Insets(0, 10, 0, 100), 0, 0));

我试图改变 weightx 和 weighty 但没有效果。更改 ipadx 和 ipady 也无济于事。我是 GridBagLayout 的新手,所以我不知道如何解决这个问题。 请帮忙!

更改布局管理器也不适合我,因为我要在面板中添加更多组件。

解决方案: 是的,正如我所料,原因在于 weightx 和 weighty 值。在我的情况下,将 weighty 设置为 0 解决了这个问题。希望这会对某人有所帮助

【问题讨论】:

  • weightx 在这里很重要,因为您使用的是 GridBagConstraints.HORIZONTAL 填充约束,但 weighty 没有效果,因为您没有使用 GridBagConstraints.BOTH 填充约束。如需更详细的答案,请考虑在您的问题中创建并发布有效的minimal reproducible example。这不是在此站点上获得答案的绝对要求,但通常可以帮助加快处理速度。
  • 在我得到 weightx/weighty 后编辑评论
  • 你试过零权重吗?你确定差距不在添加的组件中吗? (假设您不是指的是插图产生的间隙)

标签: java swing awt layout-manager gridbaglayout


【解决方案1】:

组件之间的空白空间可能是由Insets 引起的。因为这正是它们的用途。来自 javadoc:

Insets 对象是容器边界的表示。它指定容器必须在其每个边缘留下的空间。空格可以是边框、空格或标题。

如果您将Insets 中的所有条目更改为0,则空白区域应该消失:

optionsPanel.add(optionsPanelLanguageSelectorInfo,
        new GridBagConstraints(0, 0, 1, 1, wx, wy,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                new Insets(0, 0, 0, 0),//<- important part
                0, 0));

【讨论】:

  • 不,原因不在此。
  • 在这种情况下,您应该编辑您的问题并添加代码的minimal reproducable example,以便其他人可以对其进行测试。否则我们只是猜测。
猜你喜欢
  • 2015-01-18
  • 2018-02-21
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多