swing常用布局

时间:2023-03-09 03:12:43
swing常用布局

1,FlowLayout

窗口的默认布局

设置窗口布局方法(下面不重复

setLayout(new FlowLayout());

设置容器布局方法

比如容器 con1

con1.setLayout(new FlowLayout())

2.BorderLayout

        add(new JLabel("huang"),BorderLayout.CENTER);
add(new JLabel("huang"),BorderLayout.NORTH);
add(new JLabel("huang"),BorderLayout.WEST);
//如果有组件con1,con1.add(con2,bor2.CENTER)

3.GridLayout

GridLayout grid1=new GridLayout(a,b);//弄一个aXb的网格

写一个棋盘

        JPanel pane1=new JPanel();
GridLayout grid1=new GridLayout(12,12);
pane1.setLayout(grid1);
Label label[][]=new Label[12][12];
for(int i=0;i<12;i++){
for(int j=0;j<12;j++){
label[i][j]=new Label();
if((i+j)%2==0)
label[i][j].setBackground(Color.black);
else
label[i][j].setBackground(Color.white);
pane1.add(label[i][j]);
}
}
add(pane1,BorderLayout.CENTER);
add(new JButton("north"),BorderLayout.NORTH);
add(new JButton("south"),BorderLayout.SOUTH);
add(new JButton("west"),BorderLayout.WEST);
add(new JButton("east"),BorderLayout.EAST);

swing常用布局

5.BoxLayout布局

和上面的布局有点不同,语法上像一个组件一样add上去

//方法一
BoxLayout box1=new BoxLayout(Container con1,1)
//方法二
//使用Box类的静态方法
Box.createHorizontalBox()//水平盒式布局
Box.createVerticalBox()//垂直~
Box.createHorizontalStruct(int width)//空白
Box.createVerticalStruct(int height)//~
        setLayout(new FlowLayout());
Box box1,box2,boxBase;
boxBase=Box.createHorizontalBox();
box1=Box.createVerticalBox();
box1.add(new JLabel("name"));
box1.add(Box.createVerticalStrut(8));
box1.add(new JLabel("sex"));
box1.add(Box.createVerticalStrut(8));
box1.add(new JLabel("age"));
box2=Box.createVerticalBox();
box2.add(new JTextField(10));
box2.add(Box.createVerticalStrut(8));
box2.add(new JTextField(10));
box2.add(Box.createVerticalStrut(8));
box2.add(new JTextField(10));
boxBase.add(box1);
boxBase.add(Box.createHorizontalStrut(8));
boxBase.add(box2);
add(boxBase);

swing常用布局