3

Can you explain me how can I refresh value in Label?

In initialize I bind the text of the Label to a StringProperty. Here it is ok.

I have Button, and on button press I want to update the Label value in every iteration step. But I can see only the final value. Why?

@FXML
private Label label;

@FXML
private void handleButtonAction(ActionEvent event) throws InterruptedException {    
    for(int i=0;i<1001;i++){

        try {
            Thread.sleep(1);
        } catch (InterruptedException ie) {
            //Handle exception
        }            
        this.value.setValue(i+"");                 
    }
}    

// Bind 
private StringProperty value = new SimpleStringProperty("0");

@Override
public void initialize(URL url, ResourceBundle rb) {
    // Bind label to value.
    this.label.textProperty().bind(this.value);
}     
DVarga
  • 21,311
  • 6
  • 55
  • 60
David Novy
  • 89
  • 1
  • 9

1 Answers1

2

When you call Thread.sleep(1); you actually stop the JavaFX Application Thread (GUI Thread), therefore you prevent it to update the GUI.

What you basically need is a background Task which actually stops for a certain amount of time, then updates the GUI on the JavaFX Application Thread by calling Platform.runLater before it goes to sleep again.

Example:

public class MyApplication extends Application {

    private IntegerProperty value = new SimpleIntegerProperty(0);

    @Override
    public void start(Stage primaryStage) {
        try {
            HBox root = new HBox();
            Scene scene = new Scene(root, 400, 400);
            Label label = new Label();
            Button button = new Button("Press Me");

            button.setOnAction(event -> {
                // Background Task
                Task<Void> task = new Task<Void>() {
                    @Override
                    protected Void call() {

                        for (int i = 0; i < 1001; i++) {
                            int intVal = i;
                            try {
                                Thread.sleep(1);
                            } catch (InterruptedException ignored) {
                            }
                            // Update the GUI on the JavaFX Application Thread
                            Platform.runLater(() -> value.setValue(intVal));

                        }
                        return null;
                    }
                };

                Thread th = new Thread(task);
                th.setDaemon(true);
                th.start();
            });

            label.textProperty().bind(value.asString());
            root.getChildren().addAll(button, label);

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

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

Only thing left is to update the button callback.

DVarga
  • 21,311
  • 6
  • 55
  • 60