上篇文章讲述了GridBagLayout布局管理器的一些理论知识,下面将通过实例熟悉它的使用方法。
public class BWF{
public static int WIDTH=200;
public static int HEIGHT=300;
static JPanel contentPane1;
public static void add(Component c,GridBagConstraints constraints1,int x,int y,int w,int h){
constraints.gridx=x;
constraints.gridy=y;
constraints.gridwidth=w;
constraints.gridheight=h;
contentPane1.add(c,constraints1);
}
public static void main(String args[]){
JFrame jf=new JFrame("GridBagLayout实例");
jf.setSize(WIDTH, HEIGHT);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
contentPane1=new JPanel();
jf.setContentPane(contentPane1);
contentPane1.setLayout(new GridBagLayout());//将中间容器的布局管理器设置为GridBagLayout
JButton ok=new JButton("确认");
JButton cancel=new JButton("取消");
JLabel title=new JLabel("GridBagLayout布局实例");
JLabel name=new JLabel("用户名:");
JLabel password=new JLabel("密码:");
JTextField nameinput=new JTextField(15);
JTextField passwordinput=new JTextField(15);
GridBagConstraints constranints1=new GridBagConstraints();
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);
}
}