“`
package tuxingjiemian;
import java.awt.*;
import javax.swing.*;//添加AWT和Swing库文件
public class LayoutTest extends JFrame //创建类LayoutTest继承于类JFrame
{
JButton btn1,btn2,btn3,btn4,btn5;
JPanel mainPan;
FlowLayout fLayout;
GridLayout gLayout;
BorderLayout bLayout;
CardLayout cLayout;//定义布局方式
public LayoutTest(String layoutstyle) //定义构造函数
{
super(“布局方式:”+layoutstyle);
mainPan=new JPanel();
fLayout=new FlowLayout(FlowLayout.LEFT);
gLayout=new GridLayout(3,2);
bLayout=new BorderLayout();
cLayout=new CardLayout(10,10);//创建四种布局对象
if
(layoutstyle=="fLayout");
mainPan.setLayout(fLayout);
if(layoutstyle=="gLayout")
mainPan.setLayout(gLayout);
else if(layoutstyle=="bLayout")
mainPan.setLayout(bLayout);
else if(layoutstyle=="cLayout")
mainPan.setLayout(cLayout);
else
//判断采用何种布局方式
System.out.print("布局方式输入错误!");
getContentPane().add(mainPan);
btn1=new JButton("按钮1");
btn2=new JButton("按钮2");
btn3=new JButton("按钮3");
btn4=new JButton("按钮4");
btn5=new JButton("按钮5");
//创建5个按钮类
if(layoutstyle=="fLayout"||layoutstyle=="gLayout")
{
mainPan.add(btn1);
mainPan.add(btn2);
mainPan.add(btn3);
mainPan.add(btn4);
mainPan.add(btn5);
}//定义FlowLayout或者GridLayout的布局方式
if(layoutstyle=="bLayout"||layoutstyle=="cLayout")
{
mainPan.add(btn1,"East");
mainPan.add(btn2,"South");
mainPan.add(btn3,"West");
mainPan.add(btn4,"North");
mainPan.add(BorderLayout.CENTER,btn5);
}
setSize(250,150);//设置界面宽度和高度
setVisible(true);//设置界面的可见性
setDefaultCloseOperation(EXIT_ON_CLOSE);//设置窗口关闭时的默认操作
}//定义BorderLayout或者CardLayout的布局方式
public static void main(String[] args) {
// TODO Auto-generated method stub
new LayoutTest("fLayout");
new LayoutTest("gLayout");
new LayoutTest("bLayout");
new LayoutTest("cLayout");
}
}
“`
**总结:**java中容器和布局管理是分离的,也就是说,容器中组件的添加和组件的布局之间是分离的