我有这段代码,我想在Button的enum
监听器中为actionPerformed
变量设置一个值,但它说:
来自内部类的局部变量引用必须是最终的有效最终
代码:
public class myClass {
public enum UserChoice {
Yes, No
}
public void addAction() {
JButton btnYes = new JButton();
UserChoice userChoice;
btnYes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
userChoice = 1;
dlg.dispose();
}
});
}
}
我该如何解决?
答案 0 :(得分:0)
您可以将变量从Method移动到Class: (但是,如评论中所述,您的按钮不起作用)
public class myClass{
public enum UserChoice{
Yes, No
}
UserChoice userChoice;
public void addAction(){
JButton btnYes = new JButton();
btnYes.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent e){
userChoice = UserChoice.Yes;
dlg.dispose();
}
});
}
}