【发布时间】:2014-08-28 12:58:48
【问题描述】:
我能解释一下更新 GUI 线程是如何工作的吗?这对我来说都是一团糟。 例如,我想在循环中更新 ProgressBar。我知道我需要将循环放入一个新任务中。我将 progressBar 的 progressProperty 绑定到了 Task 的进度。
如果我用
调用任务new Thread(task).start();
结合调用函数中Task的updateProgress()方法,效果很好,progressBar更新了。
问题一:为什么我无法通过直接在循环内设置进度来更新 ProgressBar(progressProperty 未绑定)?如果我想在循环内设置它(不)可见,也会发生同样的情况。
问题2:让progressProperty绑定到Task.progressProperty。为什么我不能通过使用 Plateform.runLater(task) 调用 Task 来更新 progressBar?它不会更新 GUI 线程。
问题3:如何设置循环内progressBar的可见性?
public class PRogressBar extends Application {
ProgressBar progressBar;
@Override
public void start(Stage stage) {
/**
Task for updating the ProgressBar
*/
Task<Void> task = new Task() {
@Override
protected Object call() throws Exception {
System.out.println("Init Task");
// progressBar.setVisible(false) // Question 3
// progressBar.setProgress(0.75) // question 1
for (int i = 1; i < 5; i++) {
final int update = i;
try {
Thread.sleep(500);
System.out.println("Run later : " + update/5.0);
updateProgress(i, 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
};
/*
Initializing the GUI
*/
progressBar = new ProgressBar();
Button button = new Button("blou");
button.setOnAction((event) -> {
// Platform.runLater(task); // Question 2
Thread th = new Thread(task);
// th.setDaemon(true);
th.start();
System.out.println("Thread started");
});
StackPane layout = new StackPane();
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 10;");
HBox hbox = new HBox(progressBar, button);
layout.getChildren().add(hbox);
progressBar.setProgress(0.1);
// setVisible2(false);
// progressBar.progressProperty().bind(task.progressProperty());
stage.setScene(new Scene(layout));
stage.show();
}
【问题讨论】:
-
你应该继续使用
SwingUtilities#invokeLater,因为这是我在不得不使用进度条时使用的(并且工作正常) -
谢谢我开始了。然而,它是关于“Swing 中的并发”。我不认为 JavaFX 使用 Swing?有关系吗?
-
JavaFX与Swing完全不同
标签: java multithreading javafx progress-bar task