【问题标题】:How to change a variable when a button has been clicked in JavaFx在 JavaFx 中单击按钮时如何更改变量
【发布时间】:2015-04-17 05:38:55
【问题描述】:

我想在单击 JavaFX 中的按钮时更改变量。但是当我尝试使用程序中的变量时,它会说

从 lambda 内部引用的局部变量必须是 final 或有效 final。

不能让它成为最终的,因为我需要更改它以便我可以使用它。我的代码是这样的

Button next = new Button();
    next.setText("next");
    next.setOnAction((ActionEvent event) -> {
        currentLine++;
});

我能做些什么来解决这个问题?

【问题讨论】:

标签: java javafx


【解决方案1】:

您的问题有多种解决方案。除了ItachiUchiha的帖子之外,只需像这样将变量声明为类成员:

public class Main extends Application {

    int counter = 0;

    @Override
    public void start(Stage primaryStage) {
        try {
            HBox root = new HBox();
            Button button = new Button ("Increase");
            button.setOnAction(e -> {
                counter++;
                System.out.println("counter: " + counter);
            });

            root.getChildren().add( button);
            Scene scene = new Scene(root,400,400);

            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

【讨论】:

    【解决方案2】:

    概念

    annonymous inner classes 中使用的所有局部变量都应该是final or effectively final,即一旦定义,状态就不能改变。

    原因

    内部类不能引用non final局部变量的原因是,局部类实例即使在方法返回后仍可以保留在内存中,并且可以更改使用的变量的值,从而导致synchronization问题。

    你如何克服这个问题?

    1 - 声明一个为您完成工作的方法并在操作处理程序中调用它。

    public void incrementCurrentLine() {
        currentLine++;
    }
    

    以后叫它:

    next.setOnAction((ActionEvent event) -> {
        incrementCurrentLine();
    });
    

    2 - 将currentLine 声明为AtomicInteger。然后使用它的incrementAndGet() 来增加值。

    AtomicInteger currentLine = new AtomicInteger(0);

    稍后,您可以使用:

    next.setOnAction((ActionEvent event) -> {
        currentLine.incrementAndGet(); // will return the incremented value
    });
    

    3 - 您还可以声明一个自定义类,在其中声明方法并使用它们。

    【讨论】:

      猜你喜欢
      • 2022-12-23
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 2016-02-21
      • 2012-05-04
      • 1970-01-01
      相关资源
      最近更新 更多