我在互联网上搜索了解决方案,但似乎没有任何效果。
我想要做的是使用单击按钮时修改的变量“poeni”,并将结果显示在 OnActionEvent 之外的标签中。
这是我的代码中给我带来麻烦的部分。
//The button
Button rezultat = new Button("Pogledajte Vas rezultat");
rezultat.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
int poeni = 0; //The variable i want to use outside
if(odgovor1_1.isSelected()) poeni++;
if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
if(odgovor3_2.isSelected()) poeni++;
}
});
//The label in which I want to display the results
Label lbl_rezultat = new Label("Vas rezultat je: " + poeni);
最佳答案
您可以将其作为类的一个字段,以便在方法和类范围内使用它。你可以看这篇文章Scope of Variables In Java
class Rezultat{
Button rezultat = new Button("Pogledajte Vas rezultat");
int poeni;//The scope of poeni starts form here
rezultat.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
poeni = 0;
if(odgovor1_1.isSelected()) poeni++;
if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
if(odgovor3_2.isSelected()) poeni++;
}
});
Label lbl_rezultat = new Label("Vas rezultat je: " + poeni);
}//You can use variable to here
关于java - 如何在 setOnAction 外部使用定义在其内部的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43112299/