public class GraidBagLearn {
public staticvoid addComponentsToPane(Containerpane){
JButtonbutton;
pane.setLayout(new GridBagLayout());
GridBagConstraintsc=new GridBagConstraints();
c.fill=GridBagConstraints.HORIZONTAL;
c.weightx=0.5;
button=new JButton("Button1");
c.gridx=0;
c.gridy=0;
pane.add(button,c);
button=new JButton("Button2");
c.gridx=1;
c.gridy=1;
pane.add(button,c);
button=new JButton("Button3");
c.ipady=40;
c.weightx=0;
c.gridwidth=2;
c.gridx=0;
c.gridy=2;
pane.add(button,c);
button=new JButton("Button4");
c.ipady=0;
c.weighty=1;
c.anchor=GridBagConstraints.PAGE_END;
c.insets=newInsets(10,0,0,0);
c.gridx=1;
c.gridy=3;
pane.add(button,c);
}
private staticvoid createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public staticvoid main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
网格布局类似html中的表格,它将面板分成一排排,一列列的小格,将控件添加到这些小格中。GridBagConstraints指定了要添加控件的属性。
Ø gridx,gridy指定添加到那个小格中。
Ø gridwidth, gridheight指定在水平和竖直上分别要占几个小格。
Ø 如果一排有两个控件,一个的weightx为0.3,另一个的为0.7那么当把窗口拉大,水平多出100像素时,有30个分配给第一个控件,有70个分配给第二个。默认值为0,表示不分配。这是个相对值,上面指定为3和7效果一样。同理weighty指定竖直方向上的分配。
Ø c.fill=GridBagConstraints.HORIZONTAL;这个表示当格子比控件大时,控件在水平方向上充满格子,水平方向不变。还可以指定为竖直,或两者都是。
Ø c.anchor=GridBagConstraints.LAST_LINE_END;这个指定当控件比格子小时,控件应显示在那个位置,也就是上下左右,左上角,右上角等等。当然用fill指定了充满格子时,这个就没用了。
Ø c.insets=new Insets(10,0,0,0);这个指定了格子的外边框。也就是与别的格子的间距。
c. ipady=40;这类属性用来调整格子的大小,不同列不同行的格子大小可以不同。