JPanel เป็นคลาสย่อยของ JComponent เป็นคอมโพเนนต์ มองไม่เห็น (invisible) Layout เริ่มต้นคือ FlowLayout เพิ่มคอมโพเนนต์ส่วนใหญ่ได้: ปุ่ม, ช่องข้อความ, ป้าย, ตาราง, รายการ, ต้นไม้ เป็นต้น เพิ่ม sub-panels หลายตัว เข้า main panel ด้วยเมธอด add() ของ Container
ไวยากรณ์
public Component add(Component comp)
ตัวอย่าง: หลาย Sub-panels ใน Main Panel
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();
}
}
ผลลัพธ์

โครงสร้าง: JFrame → Main Panel (GridLayout 3 แถว) → JLabel หัวข้อ + Sub-panel 1 (แดง) + Sub-panel 2 (น้ำเงิน)