在GridBagLayout布局管理器中,一个组件可以跨越一个或多个网格,并可以设置各网格的大小互不相关。
import java.awt.*; public class GridBagTest {
private Frame f = new Frame("测试窗口");
private GridBagLayout gb = new GridBagLayout();
private GridBagConstraints gbc = new GridBagConstraints();
private Button[] bs = new Button[10]; public void init(){
f.setLayout(gb);
for (var i = 0; i < 10; i++){
bs[i] = new Button("button" + i);
}
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
addButton(bs[0]);
addButton(bs[1]);
addButton(bs[2]);
gbc.gridwidth = GridBagConstraints.REMAINDER;
addButton(bs[3]);
//横向不会扩展
gbc.weightx = 0;
addButton(bs[4]);
//宽度占两格,高度占一格
gbc.gridwidth = 2;
gbc.gridheight = 1;
addButton(bs[5]);
//宽度占两格,高度占一格
//gbc.gridwidth = 2;
//gbc.gridheight = 1;
gbc.gridwidth = GridBagConstraints.REMAINDER;
addButton(bs[6]); // 另起一行,宽度占一格,高度占两格。
gbc.gridwidth =1;
gbc.gridheight =2;
addButton(bs[7]);
// 纵向不再扩展,高度占一格,结束
gbc.weighty = 0;
gbc.gridwidth =GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
addButton(bs[8]);
addButton(bs[9]); f.pack();
f.setVisible(true); }
private void addButton(Button button){
gb.setConstraints(button, gbc);
f.add(button);
} public static void main(String[] args) {
new GridBagTest().init();
}
}
output: