如何在GridBagLayout中保留对齐组件?

时间:2012-07-10 03:58:57

标签: java swing gridbaglayout

enter image description here

上面图片中的每一行都是自定义组件,它使用gridbaglayout来放置组件。 我试图在按钮“Abc”之前避开那个空间,我希望它完全被推到左侧。如何使用gridbaglayout约束实现此目的?

编辑添加源代码。

        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = GridBagConstraints.NONE;
        gridBagConstraints.insets =  new Insets(11,0,0,0);
        add(abcButton,gridBagConstraints);
            gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = GridBagConstraints.NONE;
        gridBagConstraints.insets = new Insets(20, 10, 0, 0);
        add(comp1,gridBagConstraints);
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = GridBagConstraints.NONE;
        gridBagConstraints.insets = new Insets(20, 35, 0, 0);
        add(comp2, gridBagConstraints);
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 120;
        gridBagConstraints.ipady = 3;
        gridBagConstraints.fill = GridBagConstraints.NONE;
        gridBagConstraints.insets = new Insets(11,20, 0, 0);
        add(txtField1, gridBagConstraints);
    btnTxtField1.setMargin(new Insets(2, 1, 2, 1));
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 0;
        gridBagConstraints.fill = GridBagConstraints.NONE;
        gridBagConstraints.insets = new Insets(11, 0, 0, 0);
        add(btnTxtField1, gridBagConstraints);
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridx = 5;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.ipadx = 120;
    gridBagConstraints.ipady = 3;
    gridBagConstraints.fill = GridBagConstraints.NONE;
    gridBagConstraints.insets = new Insets(11, 0, 0, 0);
    add(txtField2, gridBagConstraints);
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.ipadx = 0;
    gridBagConstraints.fill = GridBagConstraints.NONE;
    gridBagConstraints.insets = new Insets(11, 0, 0, 0);
    add(btnTxtField2, gridBagConstraints);

添加重量后:

enter image description here

1 个答案:

答案 0 :(得分:3)

你必须设置一个锚到GridBagConstraints.NORTHWEST或类似的东西.......

constraints.anchor = GridBagConstraints.WEST;