5种常见的布局管理器

来源:互联网 发布:足球经理手游 知乎 编辑:程序博客网 时间:2024/05/16 16:02

1、FlowLayout------像水流一样依次进行排列

 

import java.awt.*;import javax.swing.*;public class TestFlowLayout {public static void main(String[] args) {JFrame frame = new JFrame("Hello");// 实例化窗体对象frame.setLayout(new FlowLayout(FlowLayout.CENTER,3,3));//所有组件居中对齐,水平和垂直间距为3JButton button = null;for(int i=0; i<9; i++){button = new JButton("按钮 - "+i);frame.add(button);//加入按钮}frame.setSize(280,140);//设置窗体大小frame.setVisible(true);//设置窗体可见}}


2、BorderLayout------分东南西北中五个区域

 

import java.awt.*;import javax.swing.*;public class TestBorderLayout {public static void main(String[] args) {JFrame frame = new JFrame("Hello");// 实例化窗体对象frame.setLayout(new BorderLayout(3, 3));// 水平和垂直间距都是3frame.add(new JButton("East"), BorderLayout.EAST);frame.add(new JButton("South"), BorderLayout.SOUTH);frame.add(new JButton("West"), BorderLayout.WEST);frame.add(new JButton("North"), BorderLayout.NORTH);frame.add(new JButton("Center"), BorderLayout.CENTER);frame.pack();//根据组件自动调整窗体的大小frame.setLocationRelativeTo(null);//居中frame.setVisible(true);//设置窗体可见}}


3、GridLayout------以表格形式进行排列,必须设置行数和列数

 

import java.awt.*;import javax.swing.*;public class TestGridLayout {public static void main(String[] args) {JFrame frame = new JFrame("Hello");// 实例化窗体对象frame.setLayout(new GridLayout(4,4,3,3));//4*4进行排列,水平和垂直间距都是3JButton button = null;for(int i=0; i<13; i++){button = new JButton("按钮 - "+i);frame.add(button);//加入按钮}frame.pack();//根据组件自动调整窗体的大小frame.setLocationRelativeTo(null);//居中frame.setVisible(true);//设置窗体可见}}


4、CardLayout------像一张张卡片一样,会彼此重叠,每次只展现一个界面

 

import java.awt.*;import javax.swing.*;public class TestCardLayout {public static void main(String[] args) {JFrame frame = new JFrame("Hello");// 实例化窗体对象Container cont = frame.getContentPane();//取得窗体容器CardLayout card = new CardLayout();frame.setLayout(card);cont.add(new JLabel("A",JLabel.CENTER),"first");cont.add(new JLabel("B",JLabel.CENTER),"second");cont.add(new JLabel("C",JLabel.CENTER),"third");cont.add(new JLabel("D",JLabel.CENTER),"fourth");cont.add(new JLabel("E",JLabel.CENTER),"fifth");frame.pack();//根据组件自动调整窗体的大小frame.setLocationRelativeTo(null);//居中frame.setVisible(true);//设置窗体可见card.show(cont, "third");//显示第三张卡片for(int i=0; i<5; i++){try{Thread.sleep(1000);//加入显示延迟} catch(Exception e) {e.printStackTrace();}card.next(cont);//从容器中取出组件}}}


 

5、绝对定位------设置每一个组件的具体位置

 

import javax.swing.*;public class TestAbsoluteLayout {public static void main(String[] args) {JFrame frame = new JFrame("Hello");// 实例化窗体对象frame.setLayout(null);//使用绝对定位JLabel title = new JLabel("OK");JButton enter = new JButton("Enter");JButton help = new JButton("Help");frame.setSize(200,100);title.setBounds(45,5,150,20);enter.setBounds(10,30,80,20);help.setBounds(100,30,80,20);frame.add(title);frame.add(enter);frame.add(help);frame.setLocationRelativeTo(null);//居中frame.setVisible(true);//设置窗体可见}}