java - 如何在 setOnAction 外部使用定义在其内部的变量?

标签 java button javafx

我在互联网上搜索了解决方案,但似乎没有任何效果。

我想要做的是使用单击按钮时修改的变量“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/

相关文章:

java - 替换 JavaFX GridPane 中(行,列)处的节点

java - 无法从Object转换为IntWritable

java - org.springframework.beans.factory.BeanCreationException : Error creating bean with name 'MyController' :

javascript - 单击按钮会阻止表单提交

javascript - 通过 JavaScript 向 html 元素添加属性

java - 如何将 JavaFx 的按钮更改为与此完全相同?

java - 如何使用数据库中的数据填充 JavaFX ChoiceBox?

java - 为什么我的 AsyncTask 中会出现这个 ClassCastException?

java - 无法匹配从网页读取的多行 HTML 代码

html - 通过 html 按钮(onclick)执行 shell 命令