GUI 的互動本質是事件驅動。三大核心角色:
ActionEvent),包含來源、時間戳、修飾鍵等。ActionListener) 的對象,註冊到事件源,事件觸發時回調 actionPerformed(Event e)。流程:用戶操作 → 事件源創建事件對象 → 遍歷監聽器列表調用回調 → 執行業務邏輯。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonColorDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGUI());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Event Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ButtonPanel());
frame.pack();
frame.setVisible(true);
}
}
// 繼承 JPanel 作為自定義面板,內部管理按鈕與監聽器
class ButtonPanel extends JPanel {
public ButtonPanel() {
setLayout(new FlowLayout());
JButton yellowBtn = new JButton("Yellow");
JButton redBtn = new JButton("Red");
add(yellowBtn);
add(redBtn);
// 使用內部類實現 ActionListener,便於訪問外部類成員 (如 setBackground)
yellowBtn.addActionListener(new ColorAction(Color.YELLOW));
redBtn.addActionListener(new ColorAction(Color.RED));
}
// 內部類:封裁顏色邏輯,實現閉包效果
private class ColorAction implements ActionListener {
private final Color bgColor;
public ColorAction(Color c) { this.bgColor = c; }
@Override
public void actionPerformed(ActionEvent e) {
setBackground(bgColor); // 調用外部類 ButtonPanel 的方法
repaint(); // 觸發重繪
}
}
}
ColorAction 持有外部類 ButtonPanel 的隱式引用 (this$0),可直接調用 setBackground()、repaint(),體現閉包特性。| 用戶操作 | 事件類 | 監聽器接口 | 典型組件 |
|---|---|---|---|
| 點擊按鈕/菜單/回車 | ActionEvent | ActionListener | JButton, JMenuItem, JTextField |
| 滑鼠移動/點擊/進出 | MouseEvent | MouseListener / MouseMotionListener | 所有 JComponent |
| 鍵盤輸入 | KeyEvent | KeyListener | 文本組件 |
| 窗口關閉/激活/圖標化 | WindowEvent | WindowListener | JFrame, JDialog |
| 列表/樹選擇變化 | ListSelectionEvent / TreeSelectionEvent | ListSelectionListener / TreeSelectionListener | JList, JTree |
Swing 事件模型基於觀察者模式,核心是「組件註冊監聽器,事件觸發回調」。掌握 ActionListener/ActionEvent 入門後,只需查閱對應事件類與監聽器接口,即可處理豐富的交互場景。實際開發中常使用 Lambda 表達式 (Java 8+) 簡化匿名內部類寫法,如 btn.addActionListener(e -> doSomething())。