java.awt.event.*),繼承 AWTEvent,提供 getSource() 獲取來源。EventListener 介面的類,含處理方法(如 actionPerformed)。java.awt.event.*。source.addXxxListener(listener)。| 事件類別 | 事件類 | 監聽器介面/適配器 | 核心處理方法 |
|---|---|---|---|
| 動作事件 | ActionEvent | ActionListener | actionPerformed(ActionEvent e) |
| 滑鼠事件 | MouseEvent | MouseListener / MouseAdapter | mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited |
| 滑鼠移動 | MouseEvent | MouseMotionListener / MouseMotionAdapter | mouseMoved, mouseDragged |
| 鍵盤事件 | KeyEvent | KeyListener / KeyAdapter | keyPressed, keyReleased, keyTyped |
| 視窗事件 | WindowEvent | WindowListener / WindowAdapter | windowOpened, windowClosing, windowClosed, windowActivated, windowDeactivated, windowIconified, windowDeiconified |
| 項目事件 | ItemEvent | ItemListener | itemStateChanged(ItemEvent e) |
| 調整事件 | AdjustmentEvent | AdjustmentListener | adjustmentValueChanged(AdjustmentEvent e) |
監聽器介面方法較多時,繼承對應 XxxAdapter 類,僅覆寫關心的方法,避免實現空方法。例如:
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
import java.awt.*;
import java.awt.event.*;
public class EventDemo extends Frame implements ActionListener {
Button btn = new Button("點擊我");
TextField tf = new TextField(20);
public EventDemo() {
setLayout(new FlowLayout());
add(btn);
add(tf);
btn.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
tf.setText("按鈕被點擊:" + new Date());
}
public static void main(String[] args) {
new EventDemo();
}
}
Throwable:頂層父類。
Error:JVM 級嚴重錯誤(如 OutOfMemoryError),應用無需捕獲。Exception:應用級異常,分為:
IOException、SQLException)。NullPointerException、ArrayIndexOutOfBoundsException)。try 包裹可能拋異常代碼。catch 按類型匹配處理,多 catch 由具體到通用排序。finally 無論是否異常皆執行,用於資源釋放(關閉流、鎖、連接)。public class BusinessException extends RuntimeException {
private final int errorCode;
public BusinessException(int code, String message) {
super(message);
this.errorCode = code;
}
public int getErrorCode() { return errorCode; }
}
RuntimeException,減少樣板代碼,由全局異常處理器統一捕獲轉換為錯誤響應。log.error),避免空 catch 導致故障隱形。try (InputStream in = Files.newInputStream(path)) {
// 讀取
} // 自動關閉
throw new BusinessException(500, "處理失敗", e)。public class Employee {
private String name;
private double salary;
public Employee(String name, double salary) throws IllegalSalaryException {
if (salary < 800) throw new IllegalSalaryException("薪資低於最低標準");
this.name = name;
this.salary = salary;
}
public void raiseSalary(double newSalary) throws IllegalSalaryException, IllegalRaiseException {
if (newSalary < 800) throw new IllegalSalaryException("薪資低於最低標準");
if (salary > 0 && Math.abs(newSalary - salary) / salary >= 0.2)
throw new IllegalRaiseException("漲幅超過 20%");
this.salary = newSalary;
}
}
// 自定義受檢異常
class IllegalSalaryException extends Exception {
public IllegalSalaryException(String msg) { super(msg); }
}
class IllegalRaiseException extends Exception {
public IllegalRaiseException(String msg) { super(msg); }
}
// 使用
try {
Employee emp = new Employee("張三", 5000);
emp.raiseSalary(7000);
} catch (IllegalSalaryException | IllegalRaiseException e) {
log.warn("薪資異常:{}", e.getMessage());
// 友好提示用戶
}
事件處理採用委派模型,通過監聽器解耦事件源與處理邏輯;異常處理提供結構化錯誤傳遞機制,合理使用受檢/非受檢異常、自定義異常、try-with-resources,能顯著提升代碼健壯性與可維護性。