我正在用GridBagLayout编写一个简单的awt程序,其中有四个使用gridx,gridy对角排列的按钮。当我将gridwidth设置为3时,它仅跨2列,并且忽略了自己的列。这与gridheight相同(跨度少1行)。
import java.applet.Applet;
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
public class Second extends Applet{
@Override
public void init()
{
GridBagLayout bl = new GridBagLayout();
this.setLayout(bl);
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy= 0;
gc.gridwidth = 4;
gc.fill = GridBagConstraints.HORIZONTAL;
Button btemp = new Button("Button1");
add(btemp, gc);
gc.gridx = 1;
gc.gridy= 1;
gc.gridwidth = 1;
add(new Button("Button2"), gc);
gc.gridx = 2;
gc.gridy= 2;
add(new Button("Button3"), gc);
gc.gridx = 3;
gc.gridy= 3;
add(new Button("Button4"), gc);
setVisible(true);
}
}
答案 0 :(得分:0)
问题中的原始代码如下所示:
您想要它像这样渲染,对吧?
好吧...我通过在add(new Button("Button4"), gc);
行之后添加这些行来制作该图像。 (您添加Components
的顺序似乎不会影响结果。)
//First, let us tell AWT to figure out the sizes of components
// it has so far. If we do not do this, calls to getWidth()
// will return 0 sometimes! It appears to be a race condition,
// but that's why this layoutContainer method exists.
bl.layoutContainer(this);
//Now, let us target the missing grid cell.
gc.gridx = 0;
gc.gridy = 1;
//Let us put something in there, so the whole column has a
// non-zero width. Using the width of an existing button
// is better than just picking some number of pixels.
add(Box.createHorizontalStrut(this.getComponent(2).getWidth()),gc);
//Let us adjust the applet window size (optional)
this.setSize(this.getComponent(2).getWidth() * 4, 200);
您是否愿意在网格中的那个位置粘贴不可见的组件,还是需要以其他方式解决?