如何在 Java 中向主面板添加多个子面板?
JPanel 是 JComponent 类的子类,并且是 Java 中的 不可见 组件。FlowLayout 是 JPanel 的 默认布局。我们可以将大多数组件(例如 按钮、文本字段、标签、表格、列表、树 等)添加到 JPanel 中。
我们还可以使用 Container 类的 add() 方法将 多个子面板 添加到主面板中。
语法
public Component add(Component comp)
示例
import java.awt.*;
import javax.swing.*;
public class MultiPanelTest extends JFrame {
private JPanel mainPanel, subPanel1, subPanel2;
public MultiPanelTest() {
setTitle("MultiPanel Test");
mainPanel = new JPanel(); // main panel
mainPanel.setLayout(new GridLayout(3, 1));
mainPanel.add(new JLabel("Main Panel", SwingConstants.CENTER));
mainPanel.setBackground(Color.white);
mainPanel.setBorder(BorderFactory.createLineBorder(Color.black, 1));
subPanel1 = new JPanel(); // sub-panel 1
subPanel1.add(new JLabel("Panel One", SwingConstants.CENTER));
subPanel1.setBackground(Color.red);
subPanel2 = new JPanel(); // sub-panel 2
subPanel2.setBackground(Color.blue);
subPanel2.add(new JLabel("Panel Two", SwingConstants.CENTER));
mainPanel.add(subPanel1);
mainPanel.add(subPanel2);
add(mainPanel);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new MultiPanelTest();
}
}输出
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP