关于GridBagLayout这个布局的使用以及实例

GridBagLayout是java里面最重要的布局管理器之一,可以做出很复杂的布局,可以说GridBagLayout是必须要学好的的,

GridBagLayout 类是一个灵活的布局管理器,它不要求组件的大小相同便可以将组件垂直、水平或沿它们的基线对齐。

每个 GridBagLayout 对象维持一个动态的矩形单元网格,每个组件占用一个或多个这样的单元,该单元被称为显示区域

下面就通过一个记事本案例去说明GridBagLayout的使用方法。

 

分析:

带有箭头的说明可以拉伸的。

4占用4个格子,6占用4个格子。如果设置6可以拉伸了,那么4也会跟着拉伸。

但是如果设置4拉伸,那么7所在的列也可以拉伸,所以4不能设置拉伸。我们应该设置4是跟随6进行拉伸。

灰色的线是为了看清布局的大概,组件占用的格子数。

运行时的显示效果





代码如下:

import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo extends JFrame {
JButton j1;
JButton j2;
JButton j3;
JPanel j4;
JComboBox j5;
JTextField j6;
JButton j7;
JList j8;
JTextArea j9;
public static void main(String[] args) {
GridBagLayoutDemo demo = new GridBagLayoutDemo();


}
public GridBagLayoutDemo(){
init();
this.setSize(600,600);
this.setVisible(true);
}
/**

*/
private void init() {
j1 = new JButton("打开");
j2 = new JButton("保存");
j3 = new JButton("另存为");
j4 = new JPanel();
String[] str = { "java笔记", "C++笔记", "HTML5笔记" };
j5 = new JComboBox(str);
j6 = new JTextField();
j7 = new JButton("清空");
j8 = new JList(str);
j9 = new JTextArea();
j9.setBackground(Color.PINK);//为了看出效果,设置了颜色

GridBagLayout layout = new GridBagLayout();
        this.add(j1);//把组件添加进jframe
        this.add(j2);
        this.add(j3);
        this.add(j4);
        this.add(j5);
        this.add(j6);
        this.add(j7);
        this.add(j8);
        this.add(j9);
        GridBagConstraints s = new GridBagConstraints();
        s.fill = GridBagConstraints.BOTH;
        s.gridwidth = 1;
        s.weightx =0;
        s.weighty =0;
        layout.setConstraints(j1, s);
        s.gridwidth =1;
        s.weightx =0;
        s.weighty =0;
        layout.setConstraints(j2, s);
        s.gridwidth =1;
        s.weightx =0;
        s.weighty =0;
        layout.setConstraints(j3, s);
        s.gridwidth=0;
        s.weightx=0;
        s.weighty=0;
        layout.setConstraints(j4, s);
        s.gridwidth =2;
        s.weightx =0;
        s.weighty =0;
        layout.setConstraints(j5, s);
        s.gridwidth=4;
        s.weightx=0.2;
        s.weighty=0;
        layout.setConstraints(j6, s);
        s.gridwidth=0;
        s.weightx=0;
        s.weighty=0;
        layout.setConstraints(j7, s);
        s.gridwidth=2;
        s.weightx = 0;
        s.weighty=1;
        layout.setConstraints(j8, s);
        s.gridwidth=5;
        s.weightx = 0;
        s.weighty=1;
        layout.setConstraints(j9, s);
    this.setLayout(layout);
        
}


}




原文链接:https://www.cnblogs.com/taoweiji/archive/2012/12/14/2818787.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值