【问题标题】:javafx - label does not update task progressjavafx - 标签不更新任务进度
【发布时间】:2017-11-26 01:19:53
【问题描述】:

我正在关注 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);
    }

}

【问题讨论】:

    标签: java javafx javafx-2


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多