import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* GridBagLayout使用例子 (GridBagLayout是使用最广泛的一种布局)
*
* @author brj
*/
public class TestGridBagLayout extends JFrame {
public TestGridBagLayout() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = (JPanel) getContentPane();
panel.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.weightx = 1;
constraints.insets = new Insets(5, 10, 20, 30);
constraints.fill = GridBagConstraints.BOTH;
constraints.anchor = GridBagConstraints.CENTER;
constraints.ipadx = 100;
constraints.ipady = 50;
JButton btn = new JButton("button1");
panel.add(btn, constraints);
constraints.gridx = 1;
constraints.weightx = 0;
btn = new JButton("button2");
panel.add(btn, constraints);
constraints.gridx = 2;
btn = new JButton("button3");
panel.add(btn, constraints);
constraints.gridx = 3;
btn = new JButton("button4");
panel.add(btn, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 4;
btn = new JButton("button5");
panel.add(btn, constraints);
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 3;
btn = new JButton("button6");
panel.add(btn, constraints);
constraints.gridx = 3;
constraints.gridy = 2;
constraints.gridwidth = 1;
btn = new JButton("button7");
panel.add(btn, constraints);
constraints.gridx = 0;
constraints.gridy = 3;
constraints.weighty = 1;
constraints.gridwidth = 1;
constraints.gridheight = 2;
btn = new JButton("button8");
panel.add(btn, constraints);
constraints.gridx = 1;
constraints.gridy = 3;
constraints.weighty = 0;
constraints.gridwidth = 3;
constraints.gridheight = 1;
btn = new JButton("button9");
panel.add(btn, constraints);
constraints.gridx = 1;
constraints.gridy = 4;
btn = new JButton("button10");
panel.add(btn, constraints);
pack();
}
public static void main(String[] args) {
JFrame frame = new TestGridBagLayout();
frame.setVisible(true);
}
}