GridBagLayout重量对齐

我是动态生成需要使用相对大小的布局,我发现不使用外部Java布局库的唯一方法是GridBagLayout的weightx和weighty。

在这一点上,它完全按照我的需要工作,只有一个小例外。 当我有一个包含两个JPanels的列,其空间分布分别为66.6%和33.3%,然后另一个列有3个JPanels,每个空间使用33.3%的空间,第一列的33.3%与第一列的33.3%不同占第二位的33.3%。 我需要它们完全一致。

不幸的是,这是我的第一篇文章,我无法发布任何图片,我希望我不会因为以下情况而遇到麻烦:

i.stack.imgur.com/avsuA.png

我想我知道问题是什么,在每个JPanel里面我有一个JLabel,因为weightx和weighty的定义是“Weights用于确定如何在列之间分配空间(weightx)和行之间(weighty) ”我想差异两个33.3%s之间的事实是第二列包含一个额外的JLabel。

在这个post中, StanislavL说“容器要求孩子们选择他们喜欢的大小”,所以,我想知道解决方案是否要覆盖JLabel的getPreferredSize方法。 我不确定这样做会有多“脏”,我非常感谢您解决这个问题的建议。

提前致谢!

迭戈

我想知道解决方案是否要覆盖JLabel的getPreferredSize方法。

尝试一下,除了我会覆盖面板getPreferredSize()方法,因为它会随着框架的增长/收缩而调整面板大小。

我不确定这样做会有多“脏”

overriding比使用setPreferredSize()方法更受欢迎。

我发现不使用外部Java布局库的唯一方法

如果它使代码更易于使用和理解,为什么不使用外部库? 相对布局是专为此目的而设计的,因此您无需使用尺寸。

这个问题的接受答案是:

如果Panel中的空间大于其中包含的组件的preferredDimension,则weightx和weighty用于将额外空间分配给各个组件。

weighty不会将每个箱子“锁定”到正好33%的高度; 它不会分配所有空间,只会分配额外的空间。

因此,如果您需要它们完美排列,请使用setPreferredSize (而不是按照建议覆盖getPreferredSize )。

对两列使用单个GridBagLayout而不是拆分。 GridBagLayout允许您执行的不仅仅是HTML表,而不必破解您的大小和首选大小方法。 您可以在帧初始值设定项中执行以下操作:

 getContentPane().setLayout(new GridBagLayout()); GridBagConstraints constraints = null; Insets insets = new Insets(0, 0, 0, 0); ... // upper left hand corner, 1 column wide, 2 rows high, make the column take up half of the total width, the row(s) take up 0.66 of the total height constraints = new GridBagConstraints(0, 0, 1, 2, 0.5, 0.66, GridBagConstraints.CENTER, GridBagConstraints.BOTH, insets, 0, 0); getContentPane().add(upperLeftPanel, constraints); // lower left hand corner, 1 column wide, 1 row high, make the column take up half of the total width, the row take up 0.33 of the total height constraints = new GridBagConstraints(0, 1, 1, 1, 0.5, 0.33, GridBagConstraints.CENTER, GridBagConstraints.BOTH, insets, 0, 0); getContentPane().add(lowerLeftPanel, constraints); // upper right hand corner, 1 column wide, 1 row high, make the column take up half of the total width, the row take up 0.33 of the total height constraints = new GridBagConstraints(1, 0, 1, 1, 0.5, 0.33, GridBagConstraints.CENTER, GridBagConstraints.BOTH, insets, 0, 0); getContentPane().add(upperRightPanel, constraints); // center right hand side, 1 column wide, 1 row high, make the column take up half of the total width, the row take up 0.33 of the total height constraints = new GridBagConstraints(1, 1, 1, 1, 0.5, 0.33, GridBagConstraints.CENTER, GridBagConstraints.BOTH, insets, 0, 0); getContentPane().add(centerRightPanel, constraints); // lower right hand corner, 1 column wide, 1 row high, make the column take up half of the total width, the row take up 0.33 of the total height constraints = new GridBagConstraints(1, 2, 1, 1, 0.5, 0.33, GridBagConstraints.CENTER, GridBagConstraints.BOTH, insets, 0, 0); getContentPane().add(bottomRightPanel, constraints); 

约束的各种属性以及您真正添加面板的容器完全取决于您。 您可以更改相同的约束对象或每次创建一个新对象。 我已经看到两个都使用了,但我倾向于赞成后者。 如您所见,将多个列添加到单个GridBagLayout没有问题。