简体   繁体   English

gridheight似乎不起作用

[英]gridheight doesn't seem to work

I am trying to use the GridBagLayout, but I've some trouble with it. 我正在尝试使用GridBagLayout,但是我遇到了一些麻烦。 I want to make a layout using 12 rows. 我想使用12行进行布局。 So first I make two JPanels filling up the first two rows (with gridheight = 1). 因此,首先,我使两个JPanels填充了前两行(gridheight = 1)。 Then I make 5 other JPanels to fill up the other 10 rows (with gridheight = 2). 然后,我制作另外5个JPanels来填充其他10行(gridheight = 2)。 The bottom 5 JPanels get gridheight = {2,4,6,8,10}, so they won't overlap or anything. 底部的5个JPanel获得gridheight = {2,4,6,8,10},因此它们不会重叠或其他任何东西。 The problem I get now is this: 我现在遇到的问题是:
All the JPanels get the same size! 所有的JPanel都具有相同的大小!

I also fill up BOTH ways and not using any anchors. 我还填写了两种方式,并且不使用任何锚点。 If I add a JPanel with gridx = 1, gridy = 0 and gridheight = 2, then it will have a doubled height, so what's the deal here? 如果我添加一个带有gridx = 1,gridy = 0和gridheight = 2的JPanel,那么它将具有两倍的高度,那么这有什么用呢? Do I have to tell the layout system the total amount of rows I am going to use beforehand? 我是否必须事先告知布局系统我将要使用的总行数? If so how do I do that? 如果是这样,我该怎么做?

there are several aspects to GridBagLayout (GBL) that get missed by first time users. GridBagLayout(GBL)在很多方面都被初次使用的用户所忽略。

1) components placed inside the GBL will initialize at their "preferred" size. 1)放置在GBL内的组件将以其“首选”大小进行初始化。 JPanel, iirc, has a preferred size of 1x1. iirc的JPanel的首选大小为1x1。

2) if you want the GBL cells to resize according to the enclosing container, you need to give them a weightx and weighty. 2)如果要根据封闭容器调整GBL单元的大小,则需要给它们一个weightx和weighty。 what those two attributes do is say, give the cell a percentage of the available area according to the ratio of all the weightx's and weighty's assigned. 这两个属性的作用是,根据分配的所有权重和权重之比,为单元提供可用面积的百分比。 eg if i have 2 cells and 1 has weightx = 1.0 and the second one is given 2.0, then the first cell will be 1/2 as wide as the second (or the second one will be twice as wide). 例如,如果我有2个像元,而1个像元的权重= 1.0,第二个像元的权重是2.0,那么第一个像元的宽度将是第二个像元的1/2(或者第二个像元的宽度是第二个像元的两倍)。

3) GBL takes alot of trial and error when you first dive in, BUT it is the most powerful, flexible, and reliable layout (especially compared to nested layouts, blech) 3)首次潜水时,GBL会经历很多试验和错误,但它是最强大,最灵活和最可靠的布局(尤其是与嵌套布局相比,更容易出错)

So for the first two rows I say: 因此,对于前两行,我说:

 c.fill = GridBagConstraints.HORIZONTAL;
 c.gridwidth = 1;
 c.gridheight = 1;
 c.ipadx = 100;
 c.ipady = h / (2 * columns + 2);
 c.weightx = 1.0;
 c.weighty = 1.0;

And for the next rows I only change c.ipady: 对于接下来的行,我只更改c.ipady:

 c.ipady = h / (columns + 1);

So this basically solved my problem, but I still think it could have been a lot easier. 因此,这基本上解决了我的问题,但我仍然认为这可能容易得多。

PS The variable h is the hight of my screen. PS变量h是我屏幕的最高点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM