Swing 建立在 AWT 之上,提供輕量級、跨平台的組件集。核心包:javax.swing.* (高層組件) + java.awt.* (佈局、事件、圖形底層)。所有 Swing 組件繼承自 JComponent,最終掛載在 頂層容器 (JFrame, JDialog, JApplet) 的內容面板 (ContentPane) 上。
import javax.swing.*;
import java.awt.*;
public class FirstSwing {
public static void main(String[] args) {
// 必須在 EDT 上構建 GUI
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Hello Swing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = frame.getContentPane();
cp.setLayout(new FlowLayout()); // 佈局管理器
cp.add(new JButton("Click Me"));
cp.add(new JButton("Shit"));
frame.pack(); // 自動調整到組件首選大小
frame.setVisible(true);
});
}
}
JFrame 作為根容器。getContentPane() 獲取內容面板 (實際承載組件的層)。FlowLayout 左右流式排列)。add() 將組件加入容器,構建圖形樹 (父子包含關係)。pack() + setVisible(true) 顯示窗口。容器與組件通過 add() 形成樹狀結構:JFrame → ContentPane → JPanel → JButton...。佈局管理器決定子組件的位置與大小,實現跨平台適配。
| 佈局 | 特點 | 適用場景 |
|---|---|---|
| FlowLayout | 默認,左到右,換行 | 簡單工具欄、按鈕組 |
| BorderLayout | 五大區域,中間自動撐滿 | 主窗口整體結構 |
| GridLayout | 規則網格,等寬高 | 計算器鍵盤、表格式表單 |
| GridBagLayout | 最靈活,組件可跨行列、設權重 | 複雜表單、響應式界面 |
| BoxLayout | 單行/單列,配合膠水/塊 | 工具欄、側邊欄 |
| CardLayout | 卡片疊放,一次顯示一張 | 向導頁面、Tab 切換邏輯層 |
// 示例:GridLayout 2列,展示常用組件
cp.setLayout(new GridLayout(0, 2));
cp.add(new JButton("Button"));
cp.add(new JLabel("Label"));
JPanel p1 = new JPanel(new BorderLayout());
p1.add(new JButton("Center"), BorderLayout.CENTER);
cp.add(p1);
JPanel p2 = new JPanel(new BorderLayout());
p2.setBackground(Color.RED);
p2.add(new JLabel("East"), BorderLayout.EAST);
cp.add(p2);
String[] data = {"A", "B", "C"};
cp.add(new JList(data));
cp.add(new JCheckBox("Check"));
核心組件體系:JComponent → AbstractButton (Button/CheckBox/Radio) / JLabel / JTextComponent (Field/Area) / JList / JTable / JTree / JComboBox / JSlider / JProgressBar …
Swing 以圖形樹組織界面,佈局管理器解決跨平台適配,輕量級組件提供豐富控件。理解「容器-組件-佈局」三角關係是 GUI 開發的基石。現代開發多使用 IDE 可視化設計器 (如 IntelliJ GUI Designer, NetBeans Matisse) 生成樣板代碼,但手寫能力對調試、動態構建、自定義組件至關重要。