使用 GridBagLayout (Java Swing) 在 2 个网格中居中按钮

centering a button in 2 grids using GridBagLayout (Java Swing)

我很好奇是否可以将 JButton 居中放置在 GridBagLayout 的两个 X 网格中?我已经通过 API 进行了一些搜索,但没有找到太多。我还画了一张小图来说明我要做什么。

谢谢!

示例图片:

I've done some searching through the API but haven't found much.

阅读 How to Use GridBagLayout 上的 Swing 教程部分。

您需要专注于 Specifying Constraints 部分:

  1. gridwidth 约束将允许按钮跨越多个列
  2. anchor 约束将允许按钮在两列中居中。
  3. 需要关闭 fill 约束。

以上假设您实际上在面板的每一列中都有其他组件。你不能随便说一个组件占两列。

所以从教程中的演示代码开始修改它,使底部的按钮居中。