JPanel(面板)
# 1. 概述
官方JavaDocsApi: javax.swing.JPanel (opens new window)
JPanel,面板。JPanel 是在开发中使用频率非常高的一般轻量级面板容器组件。
JPanel 常用构造方法:
// 创建默认使用流式布局的面板
JPanel()
// 创建指定布局管理器的面板
JPanel(LayoutManager layout)
1
2
3
4
5
2
3
4
5
# 2. 代码实例
package com.xiets.swing;
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
JFrame jf = new JFrame("用户登录");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// 第 1 个 JPanel, 使用默认的浮动布局
JPanel panel01 = new JPanel();
panel01.add(new JLabel("用户名"));
panel01.add(new JTextField(10));
// 第 2 个 JPanel, 使用默认的浮动布局
JPanel panel02 = new JPanel();
panel02.add(new JLabel("密 码"));
panel02.add(new JPasswordField(10));
// 第 3 个 JPanel, 使用浮动布局, 并且容器内组件居中显示
JPanel panel03 = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel03.add(new JButton("登录"));
panel03.add(new JButton("注册"));
// 创建一个垂直盒子容器, 把上面 3 个 JPanel 串起来作为内容面板添加到窗口
Box vBox = Box.createVerticalBox();
vBox.add(panel01);
vBox.add(panel02);
vBox.add(panel03);
jf.setContentPane(vBox);
jf.pack();
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
结果展示:

上次更新: 2024-09-19 12:17:39