网格包布局管理器

```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");

    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值