初學者嘗試讓 JFrame 直接實作 ActionListener 介面,但在註冊監聽器時出現型別不符錯誤。
讓主視窗類別實作 ActionListener,並正確覆寫 actionPerformed 方法:
public class Sl14 extends JFrame implements ActionListener {
// ... 元件初始化 ...
jb.addActionListener(this); // this 指向實作 ActionListener 的 JFrame 實例
@Override
public void actionPerformed(ActionEvent e) {
this.jb.setText("按鈕" + (++k) + "次");
}
}
忘記 implements ActionListener 或 actionPerformed 方法簽名錯誤(如拼寫、參數型別),會導致編譯失敗。
掌握事件處理的多種寫法,能根據專案規模靈活選擇最適合的架構。