Java AWT/Swing 采用事件委派模型處理用戶交互。本文以按鈕點擊為例,深度講解事件源、事件對象、監聽器接口、註冊機制、內部類實現與多監聽器管理,附帶完整可運行代碼範例。
JButton、JFrame)。ActionEvent 包含動作命令、修飾鍵等)。ActionListener)的對象,處理事件邏輯。addXxxListener() 將監聽器加入列表。JButton yellowBtn = new JButton("Yellow");
JButton blueBtn = new JButton("Blue");
JButton redBtn = new JButton("Red");
class ColorAction implements ActionListener {
private Color bgColor;
public ColorAction(Color c) { this.bgColor = c; }
@Override
public void actionPerformed(ActionEvent e) {
// 此處需訪問面板對象修改背景色
}
}
yellowBtn.addActionListener(new ColorAction(Color.YELLOW));
blueBtn.addActionListener(new ColorAction(Color.BLUE));
redBtn.addActionListener(new ColorAction(Color.RED));
監聽器類若為外部類,無法直接訪問面板實例。兩種解決方案:
class ColorAction implements ActionListener {
private JPanel panel;
private Color color;
public ColorAction(JPanel p, Color c) { this.panel = p; this.color = c; }
@Override public void actionPerformed(ActionEvent e) {
panel.setBackground(color);
}
}
// 使用
yellowBtn.addActionListener(new ColorAction(buttonPanel, Color.YELLOW));
public class ButtonFrame extends JFrame {
private JPanel buttonPanel;
// ...
private class ColorAction implements ActionListener {
private Color bgColor;
public ColorAction(Color c) { bgColor = c; }
@Override public void actionPerformed(ActionEvent e) {
buttonPanel.setBackground(bgColor); // 直接訪問外部類字段
}
}
// 註冊
buttonPanel.add(new JButton("Yellow")).addActionListener(new ColorAction(Color.YELLOW));
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonEventDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("按鈕事件演示");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 200));
// 內部類監聽器
class ColorAction implements ActionListener {
private Color color;
ColorAction(Color c) { color = c; }
@Override public void actionPerformed(ActionEvent e) {
panel.setBackground(color);
}
}
panel.add(new JButton("Yellow")).addActionListener(new ColorAction(Color.YELLOW));
panel.add(new JButton("Blue")).addActionListener(new ColorAction(Color.BLUE));
panel.add(new JButton("Red")).addActionListener(new ColorAction(Color.RED));
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
ActionListener,點擊時按註冊順序依次調用。ActionEvent 提供有用方法:
getActionCommand():返回按鈕文本(或 setActionCommand 設置)。getModifiers():檢查 Ctrl/Shift/Alt 是否按下。getSource():返回事件源組件引用。
btn.addActionListener(e -> {
System.out.println("命令:" + e.getActionCommand());
System.out.println("來源:" + e.getSource());
});
btn.addActionListener(e -> doSomething())。