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