如何从左上角然后垂直放置GridBaglayout中的组件?

时间:2014-08-15 18:09:01

标签: java swing location layout-manager gridbaglayout

我想把我的按钮放在PIC 2中,但它们的放置方式与PIC 1中的按钮相同。(PIC 2在油漆中编辑)。有谁知道我做错了什么?我如何从左上角然后在下一个下面放置,依此类推?

PICS:

http://imgur.com/GojL6of

这是我的代码:

public class TestTwo extends JFrame implements ActionListener {

JPanel p1 = new JPanel();
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");



public static void main(String[] args){

    new TestTwo();

}

public TestTwo(){

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

    p1.setLayout(gbl);
    add(p1, BorderLayout.WEST);

    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.weightx = 0;
    gbc.weighty = 0;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.NORTHWEST;

    p1.add(b1, gbc);

    gbc.gridheight = 1;
    gbc.gridwidth = 1;
    gbc.gridx = 0;
    gbc.gridy = 1;
    p1.add(b2, gbc);

    setLocationRelativeTo(null);
    setResizable(true);
    setSize(200, 200);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

}

@Override
public void actionPerformed(ActionEvent e) {
    // do nothing

}


}

1 个答案:

答案 0 :(得分:1)

有关如何使用GBL的更多说明,示例等,请参阅this page。这对我有用,希望它有所帮助!

public TestTwo() {
    GridBagLayout gbl = new GridBagLayout();
    GridBagConstraints gbc = new GridBagConstraints();
    setLayout(gbl);
    p1.setLayout(gbl);

    gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
            GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(
                  0, 0, 0, 0), 0, 0);
    add(p1, gbc); //add p1 in a GBL too, so it ends up in the northwest corner

    p1.add(b1, gbc);

    gbc.gridy = 1;
    p1.add(b2, gbc);

    setLocationRelativeTo(null);
    setResizable(true);
    setSize(200, 200);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}