1、绝对布局
public class Demo extends JFrame { public Demo(){ setBounds(100,100,300,300); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setVisible(true); Container c=getContentPane(); c.setLayout(null);//容器布局设为绝对布局 JButton b1=new JButton("按钮1"),b2=new JButton("按钮2"); b1.setBounds(10,10,100,40); b2.setBounds(10,100,100,40); c.add(b1); c.add(b2); } public static void main(String[] args){ new Demo(); } }
2、流布局FlowLayout,默认居中对齐。控件随窗口大小流动排列
public class Demo extends JFrame { public Demo() { setBounds(100, 100, 300, 200); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout());//容器布局设为流布局 // c.setLayout(new FlowLayout(FlowLayout.LEFT));//左对齐 // c.setLayout(new FlowLayout(FlowLayout.LEFT,20,20));//左对齐,控件间距20 for (int i = 0; i < 6; i++) { c.add(new JButton("按钮" + i)); } setVisible(true); } public static void main(String[] args) { new Demo(); } }
3、边界布局BorderLayout,容器被划分为中、东、西、南、北五个区域,默认添加在中部区域。 同一区域内新控件会覆盖旧控件。
public class Demo extends JFrame { public Demo() { setBounds(100, 100, 300, 200); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new BorderLayout());//容器布局设为边界布局 JButton b1 = new JButton("中"); JButton b2 = new JButton("东"); JButton b3 = new JButton("西"); JButton b4 = new JButton("南"); JButton b5 = new JButton("北"); c.add(b1); c.add(b2, BorderLayout.EAST); c.add(b3, BorderLayout.WEST); c.add(b4, BorderLayout.SOUTH); c.add(b5, BorderLayout.NORTH); setVisible(true); } public static void main(String[] args) { new Demo(); } }
4、网格布局GridLayout,当控件过多或过少时,自动调整布局,行数不变,列数变。
public class Demo extends JFrame { public Demo() { setBounds(100, 100, 300, 200); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new GridLayout(2,4,10,10));//网格布局,2*4,间距10 for(int i=0;i<6;i++){//6个按钮,填不满8个位置。自动调整布局为2*3,行数不变,列数变。 c.add(new JButton("按钮"+i)); } setVisible(true); } public static void main(String[] args) { new Demo(); } }