如何将int值传递给JButton actionlistener



我正在制作一个测试程序,向用户提出简单的数学问题,得到答案,计算用户的分数等

我收到一个错误,因为我在actionListener:中使用了一个变量(在本例中为x)

for(x = 0;x < total;x++){
System.out.print((x+1)+". ");
questionLabel.setText(number1" + "+ number2);
answerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
int returnedAns = Integer.parseInt(answerTextField.getText());
if(returnedAns == answerToTheQuestion){
score++;
System.out.println("correct");
question[x].result = true;
}else{
System.out.println("wrong");
question[x].result = false;
}
try{
Thread.sleep(500);
}catch(Exception e){}
}
});
}

当我运行代码时,它会突出显示int x,并表示"从内部类引用的局部变量必须是final或实际上是final"。

请帮帮我,我真的不知道该怎么办。

我不能将其标记为最终结果,因为我需要能够更改它以使for循环工作。。。

最好的方法是为这个ActionListener实现定义一个额外的类。

public class NumberedActionListener implements ActionListener {
private int number;
public NumberedActionListener(int number) {
this.number = number;
}
@Override
public void actionPerformed(ActionEvent e) {
// ...
}
}

然后可以将一个int值传递给构造函数。

answerButton.addActionListener(new NumberedActionListener(x));

如果你喜欢干净的代码,这看起来也更好。。。

您可以将x的值分配给for-循环中的另一个变量,然后使该变量成为final。

for(x = 0;x < total;x++){
final int index = x;
// use index inside your actionListener
}

最新更新