Swing 是 Java 提供的輕量級 GUI 元件套件,屬於 Java Foundation Classes (JFC) 一部分。特點如下:
import javax.swing.*;
public class HelloWorldSwing {
private static void createAndShowGUI() {
// 設定預設外觀
JFrame.setDefaultLookAndFeelDecorated(true);
// 建立視窗
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 加入標籤
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
// 顯示視窗
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// 必須在 EDT (Event Dispatch Thread) 建立 GUI
SwingUtilities.invokeLater(() -> createAndShowGUI());
}
}
SwingUtilities.invokeLater():確保 GUI 建立在事件派發執行緒中,保障執行緒安全frame.pack():自動調整視窗大小以容納所有元件setDefaultCloseOperation(EXIT_ON_CLOSE):關閉視窗時結束程式import javax.swing.*;
public class SwingLoginExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Login Example");
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null); // 使用絕對定位
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
// 帳號標籤與輸入框
JLabel userLabel = new JLabel("User:");
userLabel.setBounds(10, 20, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
// 密碼標籤與輸入框(隱藏字元)
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100, 50, 165, 25);
panel.add(passwordText);
// 登入按鈕
JButton loginButton = new JButton("login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
}
}
| 元件類別 | 用途 | 常用方法 |
|---|---|---|
| JFrame | 主視窗容器 | setSize、setVisible、setDefaultCloseOperation |
| JPanel | 面板容器,可嵌套 | setLayout、add |
| JLabel | 顯示文字/圖片 | setText、setIcon、setHorizontalAlignment |
| JTextField | 單行文字輸入 | getText、setText、setColumns |
| JPasswordField | 密碼輸入(遮罩字元) | getPassword、setEchoChar |
| JButton | 按鈕 | addActionListener、setText |
範例使用 null 版面(絕對定位),實務開發建議使用:
javac HelloWorldSwing.java
java HelloWorldSwing
Swing 提供完整的 GUI 開發能力,掌握基本元件、版面配置與事件處理機制,即可開發桌面應用程式。進階主題包含:事件監聽器模式、自訂元件繪製、多執行緒與 SwingWorker、資料綁定與表格模型等。