```java
**
## //网格包布局管理器
**
import java.awt.*;
class Layout extends Frame{
public Layout(String gridBagLayout){
GridBagLayout layout = new GridBagLayout(); //网格包布局管理器
GridBagConstraints c = new GridBagConstraints(); // 创建GridBagConstraints对象,并设置GridBagConstraints的有关属性
this.setLayout(layout); //调用本类的容器采用网格包布局管理器
c.fill = GridBagConstraints.BOTH; //设置 BOTH:使组件足够大,以填充整个显示区域
c.weightx = 1;
c.weighty = 1;
this.addComponent("btn1", layout, c);
this.addComponent("btn2", layout, c);
this.addComponent("btn3", layout, c);
//添加的组件是本行最后一个组件
c.gridwidth = GridBagConstraints.REMAINDER;
this.addComponent("btn4", layout, c);
c.weightx = 0; //设置横向比例(权重)为 0
c.weighty = 0; //设置纵向比例(权重)为 0
addComponent("btn5", layout, c);
c.gridwidth = 1; //设置组件跨 1 个网格
this.addComponent("btn6", layout, c);
//添加的组件是本行最后一个组件
c.gridwidth = GridBagConstraints.REMAINDER;
this.addComponent("btn7", layout, c);
c.gridheight = 2; //设置组件纵向跨 2 个网格
c.gridwidth = 1; //设置组件横向跨 1 个网格
c.weightx = 2; //设置横向比例(权重)为 2
c.weighty = 2; //设置横向比例(权重)为 2
this.addComponent("btn8", layout, c);
c.gridwidth = GridBagConstraints.REMAINDER; //最后一个组件
c.gridheight = 1;
this.addComponent("btn9", layout, c);
this.addComponent("btn10", layout, c);
this.setTitle("title");
this.pack();
this.setVisible(true);
}
//创建一个添加组件的方法
private void addComponent(String name, GridBagLayout layout, GridBagConstraints c) {
Button bt = new Button(name);
layout.setConstraints(bt, c);
this.add(bt);
}
}
//测试区
public class Demo05 {
public static void main(String[] args) {
new Layout("GridBagLayout");
}
}
网格包布局管理器
最新推荐文章于 2023-01-14 16:43:18 发布