package zzn;
import javax.swing.*;
public class DemoUI extends JFrame {
public static void main(String[] args) {
// 在事件調度執行緒(EDT)中啟動 GUI,確保線程安全
SwingUtilities.invokeLater(() -> {
new DemoUI().setVisible(true);
});
}
public DemoUI() {
setTitle("我的第一個 Swing 視窗");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 關閉視窗時退出 JVM
setLocationRelativeTo(null); // 視窗居中顯示
}
}
public DemoUI() {
// ... 前述初始化 ...
setLayout(new BorderLayout()); // 邊界佈局:北、南、東、西、中
JLabel label = new JLabel("Hello, Swing!", SwingConstants.CENTER);
label.setFont(new Font("微軟正黑體", Font.BOLD, 24));
add(label, BorderLayout.CENTER);
JButton btn = new JButton("點擊我");
btn.addActionListener(e -> JOptionPane.showMessageDialog(this, "按鈕被點擊了!"));
add(btn, BorderLayout.SOUTH);
}
| 佈局管理器 | 特點 | 適用場景 |
|---|---|---|
| FlowLayout | 左到右、上到下流式排列 | 簡單工具欄、按鈕組 |
| BorderLayout | 五大區域(北南東西中) | 主視窗整體結構 |
| GridLayout | 規則網格,單元格等大 | 計算機鍵盤、表格式表單 |
| GridBagLayout | 靈活網格,組件可跨行列 | 複雜表單、儀表板 |
| BoxLayout | 單行/單列堆疊 | 工具欄、側邊欄 |
// 從 classpath 載入(推薦,打包成 jar 後仍可訪問)
ImageIcon icon = new ImageIcon(getClass().getResource("/images/icon.png"));
JLabel imgLabel = new JLabel(icon);
add(imgLabel, BorderLayout.NORTH);
Swing 雖屬舊世代 GUI 技術,但零依賴、跨平台、成熟穩定,適合快速構建內部工具、教學演示或輕量級桌面應用。掌握「EDT 線程模型、佈局管理器、事件監聽」三大核心,即可輕松上手。