我想在单击 JavaFX 中的按钮时更改变量。但是当我尝试使用程序中的变量时,它会显示
local variables referenced from inside a lambda must be final or effectively final.
我无法将其最终确定,因为我需要更改它以便我可以使用它。我的代码如下所示
Button next = new Button();
next.setText("next");
next.setOnAction((ActionEvent event) -> {
currentLine++;
});
我能做些什么来解决这个问题?
最佳答案
您的问题有多种解决方案。除了 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);
}
}
关于java - 如何在 JavaFx 中单击按钮时更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29691201/