首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >JavaFX。如何更改标签的值。错误:变量必须是最终的或实际上是最终的。

JavaFX。如何更改标签的值。错误:变量必须是最终的或实际上是最终的。
EN

Stack Overflow用户
提问于 2016-05-15 18:12:13
回答 1查看 1.3K关注 0票数 0

我有一个带有按钮correctBut和标签Label pointsLbl = new Label("0")的简单窗口。我希望每次我按下按钮时,pointsLbl的文本都会改变。最初,pointsLbl的文本是"0“。然后,当我按下按钮时,应该是"1";

因此,我创建了一个额外的变量int points,它最初也是0。我认为我可以在points中添加+1,而不是将其转换为string,并将其设置为新文本。

代码语言:javascript
运行
复制
String newValStr = points.toString();
pointsLbl.setText(newValStr);

但是我得到了以下错误:“变量点是从内部类中访问的,需要是最终的或实际上是最终的”。

因此,应该如何编写代码,以便我可以更改值,然后将setText更改为pointsLbl

代码语言:javascript
运行
复制
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class QuickGameWindow {

    public static void display() {

        Stage window = new Stage();

        int points = 0;
        String parsedPoints = "";

        window.setTitle("New Window");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(10,10,10,10));
        grid.setVgap(20);
        grid.setHgap(10);

        Button correctBut = new Button("Correct");
        Label textLbl = new Label("Points - ");
        Label pointsLbl = new Label("0");

        correctBut.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {

            //Here comes the problem. I cannot change the value of points.

                points++;
                String newValStr = points.toString();
                pointsLbl.setText(newValStr);

            }
        });


        GridPane.setConstraints(correctBut, 3, 3);
        GridPane.setConstraints(pointsLbl, 1, 5);
        GridPane.setConstraints(textLbl, 3, 5);

        grid.getChildren().addAll(correctBut,pointsLbl,textLbl);
        Scene scene = new Scene(grid, 300, 200);

        window.setScene(scene);
        window.show();

    }
}
EN

回答 1

Stack Overflow用户

发布于 2016-05-15 18:22:06

在对事件处理程序使用lambda表达式时,外部作用域中定义的所有变量都必须是最终变量或成员变量。这给你留下了两个选择:

1)使计数器points成为成员变量:

代码语言:javascript
运行
复制
private int points = 0;

2)使用区域设置IntegerProperty而不是int:

代码语言:javascript
运行
复制
IntegerProperty points = new SimpleIntegerProperty(0);
...
correctBut.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent e) {
        points.set(points.get() + 1);
        String newValStr = points.toString();
        pointsLbl.setText(newValStr);
    }
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37241933

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档