我正在使用JavaFX做一个简单的UI。我创建了一个处理SQL查询和Excel文件的应用程序,然后在执行时显示进度条窗口。我已经阅读了许多推荐使用taks的其他stackoverflow问题。但是,即使使用JavaFX任务,也会显示我的进度条,但仍为空。这是我的代码:
public class ProgressBarWindow extends VBox
{
public ProgressBarWindow(Stage stage)
{
final ProgressBar pb = new ProgressBar();
pb.setProgress(ProgressBar.INDETERMINATE_PROGRESS);
Label label = new Label("Le fichier de classement est en cours de création.");
setStyle(
"-fx-padding:10; -fx-background-color: honeydew; -fx-border-color: derive(honeydew, -30%); -fx-border-width: 3;");
setPadding(new Insets(20, 20, 20, 20));
setAlignment(Pos.BASELINE_CENTER);
setSpacing(25);
getChildren().addAll(label);
getChildren().addAll(pb);
}
}
// Called when the user clicks the Finish button in a wizard
public void finish()
{
Task task = new Task<Void>()
{
@Override
public Void call()
{
try
{
StandingsCreationHelper.createStandingsFile();
}
catch (Exception ex)
{
Alert alertStandingsFileExecution = Dialog.getExceptionDialog(ex);
alertStandingsFileExecution.showAndWait();
}
return null;
}
};
new Thread(task).start();
Scene scene = new Scene(new ProgressBarWindow(owner));
owner.setScene(scene);
owner.show();
do
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
// recommended because catching InterruptedException clears interrupt flag
Thread.currentThread().interrupt();
return;
}
}
while (StandingsCreationHelper.isFinished() == false);
owner.close();
}
提前感谢您的帮助!
注意:单独运行ProgressBarWindow时(添加舞台和场景并手动显示),进度条会显示我希望看到的来回移动。
答案 0 :(得分:2)
您正在阻止FX应用程序线程,阻止它呈现。永远不要这样做。
您应该使用任务的onSucceeded
处理程序在任务完成时执行代码,并使用onFailed
处理程序来管理异常。两者都在FX Application Thread上执行,它允许您与他们进行UI交互。
public void finish() {
Task task = new Task<Void>() {
@Override
public Void call() throws Exception {
StandingsCreationHelper.createStandingsFile();
return null;
}
};
task.setOnFailed(e -> {
Throwable ex = task.getException();
Alert alertStandingsFileExecution = Dialog.getExceptionDialog(ex);
alertStandingsFileExecution.showAndWait();
});
task.setOnSucceeded(e -> owner.close());
Scene scene = new Scene(new ProgressBarWindow(owner));
owner.setScene(scene);
owner.show();
new Thread(task).start();
}