GribBagLayout gridx,gridy,gridwidth,gridy,fill

时间:2016-06-17 05:01:53

标签: gridbaglayout

我在GridBagLayout,gridx,gridy,gridwidth,gridheight和fill值上尝试了一个简单的测试程序。

程序打算显示4个按钮,

btn 5 at(0,0)wd 4 ht 1

btn 6 at(0,1)wd 12 ht 4填充宽度12和高度4

btn 1 at(4,0)wd 8 ht 1填充8的宽度

btn 2 at(0,5)wd 1 ht 1

但屏幕上的实际结果是:

Result when running the program

btn 5 at(0,0)wd 4 ht 1

btn 6 at(0,1)wd 12 ht WRONG填充宽度12和高度NOT FILLING

btn 1 at(4,0)wd 8 ht WRONG fill the width NOT FILLING

btn 2 at(12,0)而不是(0,5)

我不确定我的计划出了什么问题,有人可以帮忙吗?

以下是编码

public class t扩展了Frame {

GridBagLayout gbl = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();

public t() {
    addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e) {  
                System.exit(0);
        }
    });
    setBounds(20,20,500,500);
    setVisible(true);
    setLayout(gbl);
    Button b1 = new Button("B1");
    Button b2 = new Button("Button TWO");
    Button b5 = new Button("Button FIVE");
    Button b6 = new Button("Btn 6");

    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 4;
    c.gridheight = 1;
    add(b5,c);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 12;
    c.gridheight = 4;
    c.fill = GridBagConstraints.BOTH;
    add(b6,c);

    c.gridx = 4;
    c.gridy = 0;
    c.gridwidth = 8;
    c.gridheight = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    add(b1,c);

    c.gridx = 0;
    c.gridy = 5;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.fill = GridBagConstraints.NONE;       
    add(b2);
}

public static void main(String[] args){
    t  test = new t();
}

}

1 个答案:

答案 0 :(得分:0)

我对设定约束的原始代码进行了一些修正,下面是代码:

    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 4;
    c.gridheight = 1;
    c.weightx = 0.250;
    c.weighty = 0.167;
    c.fill = GridBagConstraints.BOTH;       

    add(b5,c);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 12;
    c.gridheight = 4;
    c.weightx = 1;
    c.weighty = 0.66;
    c.fill = GridBagConstraints.BOTH;

    add(b6,c);

    c.gridx = 4;
    c.gridy = 0;
    c.gridwidth = 8;
    c.gridheight = 1;
    c.weightx = 0.75;
    c.weighty = 0.167;
    c.fill = GridBagConstraints.BOTH;

    add(b1,c);

    c.gridx = 0;
    c.gridy = 5;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.weightx = 0;
    c.weighty = 0.167;
    c.ipadx = 25;
    c.fill = GridBagConstraints.BOTH;       

    add(b2,c);

    setVisible(true);

enter image description here

输出是我想要的。