日期:2014-05-20 浏览次数:20871 次
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class GridBagLayoutDemo extends Frame {
Label l1,l2,l3,l4;
TextField tf1,tf2,tf3;
CheckboxGroup cbg;
Checkbox cb1,cb2,cb3,cb4;
Button b1,b2;
GridBagLayout gbl;
GridBagConstraints gbc;
public GridBagLayoutDemo(String title){
super(title);
l1=new Label("用户名:");
l2=new Label("密码");
l3=new Label("重复密码");
l4=new Label("获取途径");
tf1=new TextField(20);
tf2=new TextField(20);
tf2=new TextField(20);
cbg=new CheckboxGroup(); //初始化多选框组
cb1=new Checkbox("搜索",cbg,false);
cb2=new Checkbox("朋友",cbg,false);
cb2=new Checkbox("广告",cbg,false);
cb4=new Checkbox("其他",cbg,false);
b1=new Button("提交");
b2=new Button("重置");
Panel p=new Panel(); // 创建面板 面板p
p.add(cb1);
p.add(cb2);
p.add(cb3);
p.add(cb4);
Panel p1=new Panel(); //面板p1
p1.add(b1);
p1.add(b2);
//辅助类
gbl=new GridBagLayout(); //初始化gbl 创建一个网格包对象
setLayout(gbl); //将容器设置为网格包布局
gbc=new GridBagConstraints(); //创建一个Contraints 对象
gbc.fill=GridBagConstraints.HORIZONTAL; //设置gbc的水平域
addComponent(l1,0,0,1,1); //添加标签1
addComponent(tf1,1,0,1,2);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void addComponent(Component c, int row, int col, int nrow, int ncol) {
gbc.gridx=row; //设置组件显示区域的开始边单元格
gbc.gridy=col; //顶端单元格
gbc.gridwidth=nrow; //一行的单元格数
gbc.gridheight=ncol; //一列的单元格数
gbl.setConstraints(c, gbc); //设计布局的约束条件
add(c); //组件C添加到容器
}
public static void main(String[] args) {
GridBagLayoutDemo gbld=new GridBagLayoutDemo("登陆器");
gbld.setSize(500,500);
gbld.setVisible(true);
}
}
addComponent(l1,0,0,1,1); //添加标签1 addComponent(tf1,1,0,1,2);
gbl.setConstraints(c, gbc); //设计布局的约束条件
add(c); //组件C添加到容器