package wei;
import java.awt.*; //添加AWT和Swing库文件
import javax.swing.*; //Swing库文件
public class LayoutTest extends JFrame //建立类LayouTest继承于类JFrame
{
/**
*
*/
private static final long serialVersionUID = -7697840790790026847L;
JButton btn1,btn2,btn3,btn4,btn5;
JPanel mainPan;
FlowLayout fLayout;
GridLayout gLayput;
BorderLayout blayout;
CardLayout cLayout; //定义布局方式;
public LayoutTest(String layoutstyle ) //定义构造函数
{
super("布局方式"+layoutstyle);
mainPan=new JPanel();
fLayout=new FlowLayout(FlowLayout.LEFT);
GridLayout gLayout = new GridLayout(3,2);
blayout =new BorderLayout();
cLayout = new CardLayout(10,10); //创建4种布局方式的对象;
if(layoutstyle =="fLayout")
mainPan.setLayout(fLayout);
else 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); //设置窗口关闭时的默认操作
}
public static void main(String[] args)
{
// TODO 自动生成的方法存根
new LayoutTest("fLayout");
new LayoutTest("gLayout");
new LayoutTest("bLayout");
new LayoutTest("cLayout");
}
}
知识点:
布局管理器;
FlowLayout布局;
BorderLayout布局;
CardLayout布局;
GridLayout布局;
GridBagLayout布局;
NULL布局;