第13章 Swing程序组件----常用布局管理器

在Swing中,每个组件在容器中都有一个具体的位置和大小,而在容器中摆放各种组件时很难判断其具体位置和大小。布局管理器提供了Swing组件安排、展示在容器中的方法及基本的布局功能。

Swing提供的常用布局管理器包括流布局管理器、边界布局管理器和网格布局管理器

1、流布局管理器

 1 import java.awt.*;
 2 
 3 import javax.swing.*;
 4 
 5 public class FlowLayoutPosition extends JFrame {
 6     /**
 7      * 
 8      */
 9     private static final long serialVersionUID = 1L;
10 
11     public FlowLayoutPosition() {
12         setTitle("本窗体使用流布局管理器"); // 设置窗体标题
13         Container c = getContentPane();
14         // 设置窗体使用流布局管理器,使组件右对齐,并且设置组件之间的水平间隔与垂直间隔
15         setLayout(new FlowLayout(2, 10, 10));
16         for (int i = 0; i < 10; i++) { // 在容器中循环添加10个按钮
17             c.add(new JButton("button" + i));
18         }
19         setSize(300, 200); // 设置窗体大小
20         setVisible(true); // 设置窗体可见
21         // 设置窗体关闭方式
22         setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
23     }
24     
25     public static void main(String[] args) {
26         new FlowLayoutPosition();
27     }
28 }

     

2、边界布局管理器

 1 import java.awt.*;
 2 
 3 import javax.swing.*;
 4 
 5 public class BorderLayoutPosition extends JFrame {
 6     /**
 7      * 
 8      */
 9     private static final long serialVersionUID = 1L;
10     // 定义组件摆放位置的数组
11     String[] border = { BorderLayout.CENTER, BorderLayout.NORTH,
12             BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.EAST };
13     String[] buttonName = { "center button", "north button",
14             "south button", "west button", "east button" };
15     
16     public BorderLayoutPosition() {
17         setTitle("这个窗体使用边界布局管理器");
18         Container c = getContentPane(); // 定义一个容器
19         setLayout(new BorderLayout()); // 设置容器为边界布局管理器
20         for (int i = 0; i < border.length; i++) {
21             // 在容器中添加按钮,并设置按钮布局
22             c.add(border[i], new JButton(buttonName[i]));
23         }
24         setSize(350, 200); // 设置窗体大小
25         setVisible(true); // 使窗体可视
26         // 设置窗体关闭方式
27         setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
28     }
29     
30     public static void main(String[] args) {
31         new BorderLayoutPosition();
32     }
33 }

3、网格布局管理器

 1 import java.awt.*;
 2 
 3 import javax.swing.*;
 4 
 5 public class GridLayoutPosition extends JFrame {
 6     /**
 7      * 
 8      */
 9     private static final long serialVersionUID = 1L;
10 
11     public GridLayoutPosition() {
12         Container c = getContentPane();
13         // 设置容器使用网格布局管理器,设置7行3列的网格
14         setLayout(new GridLayout(7, 3, 5, 5));
15         for (int i = 0; i < 20; i++) {
16             c.add(new JButton("button" + i)); // 循环添加按钮
17         }
18         setSize(300, 300);
19         setTitle("这是一个使用网格布局管理器的窗体");
20         setVisible(true);
21         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
22     }
23     
24     public static void main(String[] args) {
25         new GridLayoutPosition();
26     }
27 }

原文地址:https://www.cnblogs.com/chamie/p/4702039.html