0

我有一个使用 javaFx(java 版本 1.8.101)创建的简单 gui,带有一个按钮和进度条。我想在按下按钮后立即更新进度。在“事件按下按钮”内,我还有一个简单的 for 循环,可以多次打印一条消息。问题是进度条仅在打印消息循环结束时更新,而不是同时独立于它。这是控制器类

    package sample;

import com.sun.javafx.tk.Toolkit;
import javafx.beans.property.Property;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ProgressBar;

public class Controller {
    @FXML
    ProgressBar progressBar;


    @FXML
    private void handleStartBtnAction(ActionEvent event) throws InterruptedException {

        final int size = 100;
        Task<Integer> t = new Task<Integer>() {
            @Override
            protected Integer call() throws Exception {
                int iterations;
                for (iterations = 0; iterations < size; iterations++) {
                    if (isCancelled()) {                        
                        break;
                    }                  
                    updateProgress(iterations, size);
                    System.out.println("update message " + iterations);
                    Thread.sleep(100);

                }
                return iterations;
            }
        };
        this.progressBar.progressProperty().bind((Property<Number>) t.progressProperty());
        Thread th = new Thread(t);
        th.setDaemon(true);
        th.start();

        for (int i = 0; i < 500000; i++) {
            System.out.println("print message " + i);

        }
    }

}
4

0 回答 0