Swing 是 Java 內建的 GUI 工具雖然歷史悠久,但仍是學習桌面應用程式開發的絕佳入門選擇。本文將引導你從零建立一個簡單的 Swing 視窗,並解析核心元件與佈局管理的基本概念。
import javax.swing.*;
import java.awt.*;
public class SwingDemo {
public static void main(String[] args) {
// 1. 建立主視窗
JFrame frame = new JFrame("Swing 入門範例");
// 2. 取得內容容器
Container container = frame.getContentPane();
// 3. 設定版面配置:FlowLayout 靠左,間距 20px
container.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 20));
// 4. 加入元件並設定屬性
JLabel label1 = new JLabel("Hello World!");
JLabel label2 = new JLabel("Bye World!");
label1.setBackground(Color.BLUE);
label1.setOpaque(true); // 必須設為 true 才會顯示背景色
container.add(label1);
container.add(label2);
// 5. 設定視窗屬性
frame.setSize(300, 150);
frame.setLocationRelativeTo(null); // 置中顯示
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 關閉視窗結束程式
frame.setVisible(true);
}
}
| 類別/方法 | 說明 |
|---|---|
JFrame | 頂層視窗容器,提供標題列、邊框、關閉按鈕等原生視窗功能。 |
getContentPane() | 取得內容面板,所有可見元件皆加入此容器。 |
FlowLayout | 流式佈局,元件依序水平排列,超過寬度自動換行。 |
JLabel | 顯示文字或圖示的標籤元件。 |
setOpaque(true) | 設定元件不透明,使背景色生效。 |
setDefaultCloseOperation(EXIT_ON_CLOSE) | 設定點擊關閉鈕時終止 JVM。 |
展示 GridLayout、事件監聽、自訂元件繼承 JButton 的實作:
package com.example.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TicTacToeGame extends JFrame {
private JPanel boardPanel = new JPanel();
public TicTacToeGame() {
Container cp = getContentPane();
cp.add(boardPanel);
boardPanel.setLayout(new GridLayout(3, 3));
for (int i = 0; i < 9; i++) {
boardPanel.add(new XOButton());
}
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TicTacToeGame::new);
}
}
class XOButton extends JButton implements ActionListener {
private final ImageIcon xIcon = new ImageIcon(getClass().getResource("x.png"));
private final ImageIcon oIcon = new ImageIcon(getClass().getResource("o.png"));
private byte state = 0; // 0:空, 1:X, 2:O
public XOButton() {
addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
state = (byte)((state + 1) % 3);
switch (state) {
case 0: setIcon(null); break;
case 1: setIcon(xIcon); break;
case 2: setIcon(oIcon); break;
}
}
}
注意:需在 classpath 下放置 x.png、o.png 圖片檔。
BorderLayout、GridLayout、BoxLayout、GridBagLayout 等,才能設計美觀且自適應的介面。ActionListener、MouseListener 等)是互動程式的基礎。SwingWorker 或 SwingUtilities.invokeLater 避免阻塞 EDT (Event Dispatch Thread)。add 到容器,且在 setVisible(true) 之前完成所有元件加入。setOpaque(true) 並確保元件不透明。
getClass().getResource("/path/img.png") 取得資源路徑,確認圖片已打包進 JAR 或輸出目錄。Swing 雖非最新技術,但其簡單直觀的 API 非常適合建立 GUI 程式設計的基本觀念。動手實作幾個小專案,你就能掌握事件處理、佈局管理與元件客製化的核心技巧。