package shirong;
import java.awt.*;
import javax.swing.*;
public class Layouttest extends 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") //start.判断采用何种布局方式,
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.println("布局方式输入错误!");
getContentPane().add(mainPan);
btn1=new JButton("按钮1");
btn2=new JButton("按钮2");
btn3=new JButton("按钮3");
btn4=new JButton("按钮4");
btn5=new JButton("按钮5");
if(layoutstyle=="flayout"||layoutstyle=="glayoyt")/*start.定义BorderLayout或者CardLayout的布局方式。*/
{
mainPan.add(btn1);
mainPan.add(btn2);
mainPan.add(btn3);
mainPan.add(btn4);
mainPan.add(btn5);
}
if(layoutstyle=="blayout"||layoutstyle=="clayout")//start.定义BorderLayout或者CardLayout的布局方式。
{
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 Auto-generated method stub
new Layouttest("flayout");
new Layouttest("glayout");
new Layouttest("blayout");
new Layouttest("clayout");
}
}
知识要点:
1.布局管理器
2.FlowLayout布局
3.BorderLayout布局
4.CardLayout布局
5.GridLayout布局
6.GridBagLayout布局
7.UNULL布局