問題代碼
this.button = new JButton(Img);
this.button.setBounds(x, y, w, h);
this.button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
this.button.setEnable(fasle); // 兩處錯誤
}
});
this.add(this.panal); // 應添加 button
錯誤分析
- 方法名拼寫錯誤:
setEnable → 正確是 setEnabled (過去分詞)。
- 參數拼寫錯誤:
fasle → 正確是 false。
- 匿名類 this 指向錯誤:匿名類內部
this 指向 ActionListener 實例,無 button 字段。應用外部類引用或將 button 定義為 final/effectively final 變量。
- 面板添加錯誤:
this.add(this.panal) 應為 this.add(this.button)。
修正代碼
final JButton btn = new JButton(img);
btn.setBounds(x, y, w, h);
btn.addActionListener(e -> {
btn.setEnabled(false); // 正確拼寫
});
this.add(btn); // 添加按鈕而非面板
最佳實踐
- 使用 IDE 自動完成避免拼寫錯誤。
- Lambda 表達式簡化監聽器,自動捕獲外部 final 變量。
- 佈局管理器優於
setBounds,實現跨平台自適應。