上篇文章讲述了GridBagLayout布局管理器的一些理论知识,下面将通过实例熟悉它的使用方法。
publicclassBWF{
publicstaticintWIDTH=400;
publicstaticintHEIGHT=300;
staticJPanelcontentPane1;
publicstaticvoidadd(Component c,GridBagConstraints constraints1,intx,inty,intw,inth){
constraints.gridx=x;
constraints.gridy=y;
constraints.gridwidth=w;
constraints.gridheight=h;
contentPane1.add(c,constraints1);
}
publicstaticvoidmain(String args[]){
JFrame jf=newJFrame("GridBagLayout实例");
jf.setSize(WIDTH,HEIGHT);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
contentPane1=newJPanel();
jf.setContentPane(contentPane1);
contentPane1.setLayout(newGridBagLayout());//将中间容器的布局管理器设置为GridBagLayout
JButton ok=newJButton("确认");
JButton cancel=newJButton("取消");
JLabel title=newJLabel("GridBagLayout布局实例");
JLabel name=newJLabel("用户名:");
JLabel password=newJLabel("密码:");
JTextField nameinput=newJTextField(15);
JTextField passwordinput=newJTextField(15);
GridBagConstraints constranints1=newGridBagConstraints();
constranints1.fill=GridBagConstraints.NONE;
constranints1.anchor=GridBagConstraints.CENTER;
constranints1.weightx=3;
constranints1.weighty=4;
add(title,constranints,0,0,4,1);
add(name,constranints,0,1,1,1);
add(password,constranints,0,2,1,1);
add(nameinput,constranints,2,1,1,1);
add(passwordinput,constranints,2,2,1,1);
add(ok,constranints,0,3,1,1);
add(cancel,constranints,2,3,1,1);
}
}
网友评论