javafx - 标签不更新任务进度

javafx - label does not update task progress

我在 javafx 中关注 Tasks 上的一个简单示例,其中 Label 文本随任务进度更新。

出于某种原因,Label 没有显示进度,而是从 -1 跳到 1(最终值)。

感谢您的帮助!

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

}

您没有正确使用 Thread with Thread.run 您只是执行代码而没有创建新线程。将 t.run(); 更改为 t.start();