Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

java - How to change a variable when a button has been clicked in JavaFx

I want change a variable when I click a button in JavaFX. But when I try to use the variable from the program it says

local variables referenced from inside a lambda must be final or effectively final.

I can't make it final though because I need to change it so I can use it. My code looks like this

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

what can i do to get around this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are various solutions to your problem. In addition to ItachiUchiha's post, simply declare the variable as class member like this:

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...