布局管理:组件在面板中的排列方式
布局管理器:LayoutManager
常见的布局:
- FlowLayout 流式布局
- BordLayout 边框布局
- GridLayout 网格布局
- CardLayout 卡片布局
- 空布局
package org.lanqiao.layout.demo;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BordLayoutDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("布局演示");
frame.setSize(420, 300);
frame.setLocationRelativeTo(null);//设置组件相对父容器的位置 null 代表居中
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*JPanel panel = new JPanel(new BorderLayout());//使用边框布局
frame.add(panel);
JButton but1 = new JButton("上边");
JButton but2 = new JButton("下边");
JButton but3 = new JButton("左边");
JButton but4 = new JButton("右边");
JButton but5 = new JButton("中间");
panel.add(but1,BorderLayout.NORTH);
panel.add(but2,BorderLayout.SOUTH);
panel.add(but3,BorderLayout.WEST);
panel.add(but4,BorderLayout.EAST);
panel.add(but5,BorderLayout.CENTER);*/
/*JPanel panel = new JPanel(new GridLayout(3, 2));//网格布局
JButton but1 = new JButton("上边");
JButton but2 = new JButton("下边");
JButton but3 = new JButton("左边");
JButton but4 = new JButton("右边");
JButton but5 = new JButton("中间");
panel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
panel.add(but1);
panel.add(but2);
panel.add(but3);
panel.add(but4);
panel.add(but5);
frame.add(panel);*/
//空布局
JPanel panel = new JPanel(null);//不采用任何的布局方式
JButton but1 = new JButton("上边");
JButton but2 = new JButton("下边");
JButton but3 = new JButton("左边");
JButton but4 = new JButton("右边");
JButton but5 = new JButton("中间");
panel.add(but1);
but1.setBounds(100, 80, 150, 150);
frame.add(panel);
frame.setVisible(true);
}
}