简体   繁体   中英

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?

Concept

All the local variables used inside annonymous inner classes should be final or effectively final ie there state cannot change once defined.

Reason

The reason inner classes cannot reference non final local variables is because the local class instance can remain in memory even after the method returns and can change the value of the variable used causing synchronization issues.

How do you overcome this ??

1 - Declare a method which does the job for you and call it inside the action handler.

public void incrementCurrentLine() {
    currentLine++;
}

later call it:

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

2 - Declare currentLine as AtomicInteger . Then use its incrementAndGet() to increment the value.

AtomicInteger currentLine = new AtomicInteger(0);

later, you can use:

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

3 - You can also declare a custom class, have methods declared in it and use them.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM