AWT為重量級組件,依賴作業系統原生Peer,外觀受平台限制、功能單薄。Swing建構於AWT之上,純Java繪製輕量級組件,跨平台一致、組件豐富(JTable、JTree、JTabbedPane等)、支援Pluggable Look & Feel。嚴禁混用:層級(Z-Order)錯亂導致AWT組件永遠覆蓋Swing組件。
JButton、JFrame等)ActionEvent、WindowEvent、MouseEvent等)ActionListener、WindowListener等)source.addXxxListener(listener)適配器模式簡化代碼:WindowAdapter實作WindowListener所有方法為空,僅覆寫關心事件(如windowClosing、windowActivated)。
JFrame frame = new JFrame("標題");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 關閉即退出
frame.setSize(400, 300); // 或 frame.pack() 自適應
frame.setVisible(true); // 顯示
組件必須加入ContentPane:frame.getContentPane().add(component)或frame.add(component)(JDK 5+語法糖)。
| 組件 | 狀態 | 監聽器 | 關鍵方法 | 群組管理 |
|---|---|---|---|---|
JButton | 無狀態 | ActionListener | actionPerformed | — |
JToggleButton | 按下/彈起 | ActionListener | isSelected() | — |
JCheckBox | 勾選/未勾選 | ItemListener | isSelected()、itemStateChanged | — |
JRadioButton | 單選 | ActionListener | isSelected() | ButtonGroup(單選互斥) |
注意:JCheckBox觸發項目事件(ItemEvent),須用ItemListener而非ActionListener。
JTextField:單行,建構子指定欄寬new JTextField(20),addCaretListener即時監聽游標/內容變化JPasswordField:繼承JTextField,setEchoChar('*')遮罩顯示,getPassword()回傳char[](安全性優於getText())JTextArea:多行,setLineWrap(true)自動換行,不自帶滾動條,必須包裹於JScrollPane| 佈局 | 特性 | 添加語法 | 適用場景 |
|---|---|---|---|
FlowLayout | 左→右、上→下流式排列,自動換行 | container.add(comp) | 簡單表單、工具列 |
BorderLayout | 五區域(NORTH/SOUTH/EAST/WEST/CENTER),各限一組件 | container.add(comp, BorderLayout.CENTER) | 主視窗整體架構 |
JPanel組合拳:區域限一組件時,用JPanel(預設FlowLayout)裝載多組件,再將JPanel置入BorderLayout區域。JScrollPane包裹JTextArea解決滾動與佈局衝突。
public class EditorFrame extends JFrame {
public EditorFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 北部工具列
JPanel toolbar = new JPanel(new FlowLayout(FlowLayout.LEFT));
toolbar.add(new JButton("開啟"));
toolbar.add(new JButton("儲存"));
add(toolbar, BorderLayout.NORTH);
// 中部編輯區
JTextArea area = new JTextArea();
area.setLineWrap(true);
add(new JScrollPane(area), BorderLayout.CENTER);
pack(); setLocationRelativeTo(null); setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(EditorFrame::new); // EDT啟動
}
}
JTable/JTree/JList中的應用paintComponent)、Look & Feel切換SwingWorker避免EDT阻塞