Java中FlowLayout,GridLayout和BorderLayout详解
一、流程布局(FlowLayout)
顾名思义, FlowLayout
是一种布局,它允许组件流到可见部分的末端。 FlowLayout
基本上有助于开发响应速度更快的UI,并使组件保持自由流动的方式。 下图显示了具有6个组件的实际流布局。
由于这是框架或面板的默认布局,因此也可以在不显式应用布局的情况下工作。
import java.awt.Button;
import java.awt.FlowLayout;
import javax.swing.JFrame;
public class FlowLayoutExample extends JFrame {
public static void main(String[] args) {
FlowLayoutExample a = new FlowLayoutExample();
}
public FlowLayoutExample() {
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
FlowLayout g = new FlowLayout();
setLayout(g);
setTitle("Flow Layout");
setSize(300, 300);
add(new Button("Button 1"));
add(new Button("Button 2"));
add(new Button("Button 3"));
add(new Button("Button 4"));
add(new Button("Button 5"));
add(new Button("Button 6"));
}
}
运行结果:
二、网格布局(GridLayout)
GridLayout
是排列组件的一种更有组织的方式。 它以包含均匀分布的单元格的网格形式划分框架或面板。 每个组件都添加到特定的单元格中。 组件的放置顺序直接取决于将它们添加到框架或面板的顺序。 下图显示了基于2列3行GridLayout
的Frame。
构造函数GridLayout(int row,int cols)
确定网格大小。
import java.awt.Button;
import java.awt.GridLayout;
import javax.swing.JFrame;
public class GridLayoutExample extends JFrame {
public static void main(String[] args) {
GridLayoutExample a = new GridLayoutExample();
}
public GridLayoutExample() {
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout g = new GridLayout(3, 2);
setLayout(g);
setTitle("Grid Layout");
setSize(300, 300);
add(new Button("Button 1"));
add(new Button("Button 2"));
add(new Button("Button 3"));
add(new Button("Button 4"));
add(new Button("Button 5"));
add(new Button("Button 6"));
}
}
运行结果:
三、边框布局(BorderLayout)
BorderLayout
是一种按照方向组织组件的布局。 边框布局将框架或面板分为5个部分-北,南,东,西和居中。 通过传递附加参数,可以将每个组件按特定方向排列
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Label;
import javax.swing.JFrame;
public class BorderLayoutExample extends JFrame {
public static void main(String[] args) {
BorderLayoutExample a = new BorderLayoutExample();
}
public BorderLayoutExample() {
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
BorderLayout b = new BorderLayout();
setTitle("Border Layout");
setSize(300, 300);
add(new Button("North"), BorderLayout.NORTH);
add(new Button("South"), BorderLayout.SOUTH);
add(new Button("East"), BorderLayout.EAST);
add(new Button("West"), BorderLayout.WEST);
add(new Button("Center"), BorderLayout.CENTER);
}
}
运行结果:
运行结果: