javafx - label不会更新任务进度

时间:2022-07-25 17:01:26

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

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

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

由于某种原因,Label不会显示进度,而是从-1跳转到1(最终值)。

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

}

1 个解决方案

#1


2  

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

您没有正确使用Thread with Thread.run,您只需执行代码而无需创建新线程。改变t.run(); to t.start();

#1


2  

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

您没有正确使用Thread with Thread.run,您只需执行代码而无需创建新线程。改变t.run(); to t.start();