tenticon
tenticon

Reputation: 2913

javafx - label does not update task progress

I am following an easy example on Tasks in javafx where a Label text is updated by the progress of the task.

For some reason the Label doesn't show the progress but jumps from -1 to 1 (the final value).

Thanks for the help!

public class MultithreadingMain extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception
    {
        HBox root = new HBox();

        Button button = new Button("Go");

        Task<Integer> task = new Task<Integer>() {
            @Override
            public Integer call() throws InterruptedException
            {
                int max = 100;
                for(int i=0; i<max; i++)
                {
                    Thread.sleep(50);
                    updateProgress(i+1,max);
                }
                System.out.println("Done");
                return 0;
            }
        };

        button.setOnAction(e -> {
            Thread t = new Thread(task);
            t.run();
        });

        Label label = new Label("");
        label.textProperty().bind(task.progressProperty().asString());

        root.getChildren().add(button);
        root.getChildren().add(label);

        Scene scene = new Scene(root, 400,400);
        primaryStage.setTitle("Multithreading in java fx");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

}

Upvotes: 1

Views: 237

Answers (1)

Edwardth
Edwardth

Reputation: 707

You are not correctly using Thread with Thread.run you just execute the code without creating a new thread. Change t.run(); to t.start();

Upvotes: 2

Related Questions