使用GridBagLayout(Java Swing)在两个网格中居中一个按钮。

huangapple go评论65阅读模式
英文:

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

问题

我想知道是否有可能在GridBagLayout的两个X网格中居中一个JButton?我已经在API中进行了一些搜索,但没有找到太多信息。我还画了一张小图片,以阐明我的尝试。

谢谢!

示例图片:

英文:

I am curious if it possible to center a JButton in two X grids of a GridBagLayout? I've done some searching through the API but haven't found much. I have also drawn up a small picture to clarify what I am trying to do.

Thank you!

Example Image:

使用GridBagLayout(Java Swing)在两个网格中居中一个按钮。

答案1

得分: 1

> 我已经通过API进行了一些搜索,但并没有找到太多信息。

阅读Swing教程中关于如何使用GridBagLayout的部分。

您需要关注“指定约束”部分:

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

上述假设您实际上在每列中的面板上有其他组件。您不能随意地让单个组件占用两列。

因此,请从教程中的演示代码开始,并将其修改为底部居中显示按钮。

英文:

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

Read the section from the Swing tutorial on How to Use GridBagLayout.

You would need to concentrate on the Specifying Constraints section:

  1. the gridwidth constraint will allow the button to span multiple columns
  2. the anchor constraint will allow the button to be centered within the two columns.
  3. the fill constraint will need to be turned off.

The above assumes that you actually have other components on the panel in each of the columns. You can't just randomly say a single component takes up two columns.

So start with the demo code in the tutorial an modify it to have the button on the bottom centered.

huangapple
  • 本文由 发表于 2020年9月24日 23:07:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64049282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定