button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 處理邏輯
}
});
// 獨立類
class ClearButtonListener implements ActionListener {
private JTextField operand1, operand2, result;
public ClearButtonListener(JTextField o1, JTextField o2, JTextField r) {
this.operand1 = o1; this.operand2 = o2; this.result = r;
}
@Override
public void actionPerformed(ActionEvent e) {
operand1.setText("");
operand2.setText("");
result.setText("");
}
}
// 註冊
clear.addActionListener(new ClearButtonListener(operand1, operand2, result));
public class Calculator extends JFrame implements ActionListener {
private JComboBox<Integer> operatorBox;
private JTextField operand1, operand2, result;
private JButton btnCalc, btnClear;
public Calculator() {
// ... 初始化元件 ...
btnCalc.addActionListener(this);
btnClear.addActionListener(this);
operatorBox.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == operatorBox) {
// 切換運算符顯示
} else if (src == btnCalc) {
// 計算邏輯
} else if (src == btnClear) {
// 清空邏輯
}
}
}
actionPerformed 易膨脹為巨大 switch/if-else。完整程式碼展示匿名類註冊下拉選單(切換 +/−)、計算按鈕、清除按鈕:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComboBoxTest extends JFrame {
private JComboBox<Integer> operatorBox = new JComboBox<>(new Integer[]{0, 1});
private JTextField operand1 = new JTextField(10);
private JLabel operatorLabel = new JLabel("+");
private JTextField operand2 = new JTextField(10);
private JTextField result = new JTextField(4);
private JButton btnCalc = new JButton("Done");
private JButton btnClear = new JButton("Clear");
public ComboBoxTest() {
// 下拉選單事件:切換運算符顯示
operatorBox.addActionListener(e -> {
operatorLabel.setText(operatorBox.getSelectedIndex() == 0 ? " + " : " - ");
});
// 計算按鈕事件
btnCalc.addActionListener(e -> {
try {
int a = Integer.parseInt(operand1.getText());
int b = Integer.parseInt(operand2.getText());
int res = (operatorBox.getSelectedIndex() == 0) ? a + b : a - b;
result.setText("= " + res);
} catch (NumberFormatException ex) {
result.setText("輸入錯誤");
}
});
// 清除按鈕事件
btnClear.addActionListener(e -> {
operand1.setText("");
operand2.setText("");
result.setText("");
});
setLayout(new FlowLayout());
add(new JLabel("選擇運算: 0(+) 1(-)"));
add(operatorBox);
add(operand1);
add(operatorLabel);
add(operand2);
add(result);
add(btnCalc);
add(btnClear);
setSize(350, 140);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(ComboBoxTest::new);
}
}
| 場景 | 推薦寫法 |
|---|---|
| 單一元件、簡單邏輯 | 匿名類 / Lambda (Java 8+) |
| 多元件共用相同邏輯 | 獨立監聽器類 |
| 表單類視窗、事件數量少 | 統一實作 ActionListener |
| 複雜業務、需單元測試 | 獨立類 + 依賴注入 |
String line; while ((line = br.readLine()) != null) { ... }e.getSource() == btn 正確,因為比較的是同一物件引用。SwingUtilities.invokeLater() 啟動 GUI。