我的主要目标是通过按不同的三个按钮获得分数,一轮一轮累计直到达到目标分数即为成功。
以下是我的java代码块
public static void main(String args[]){
FirstFrame game = new FirstFrame();
game.init();
int goal=10;
int current = 0;
while (current<goal){
game.one.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
current+=1;
}
});
}
}
运行以上代码后的error提示为
Variable 'current' is accessed from within inner class, needs to be final or effectively final
以下是我的awt界面
4到13行删掉,改成:
1.让FirstFrame实现ActionListener接口,
2.FirstFrame的初始化里对三个按钮添加监听器
game.one.addActionListener(this);
game.two.addActionListener(this);
game.three.addActionListener(this);
3.actionPerformed写在FirstFrame里。
4.下面两个变量也定义在FirstFrame里,作为类变量
int goal=10;
int current = 0;
5.actionPerformed方法这样写
public void actionPerformed(ActionEvent e) {
//通过e.getActionCommand可以得到点击了哪个按钮。
if(current<goal){
current+=1;
} else {
//超过10的代码逻辑写在这里
}
}