2016-11-18 55 views
2

我在做一個使用JavaFX的簡單UI。我創建了一個處理SQL查詢和Excel文件的應用程序,然後在執行時顯示進度欄窗口。我讀過許多其他推薦使用taks的stackoverflow問題。但是,即使使用JavaFX任務,我的進度條也會顯示,但仍爲空。這裏是我的代碼: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(添加舞臺和場景並手動顯示它)時,進度條會顯示我希望看到的來回移動。

回答

2

您正在阻止FX應用程序線程,從而無法呈現它。永遠不要這樣做。

您應該使用任務的onSucceeded處理程序在任務完成時執行代碼,並使用onFailed處理程序來管理異常。兩者都在FX應用程序線程上執行,它允許您從它們與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(); 

} 
+0

您的代碼更清潔,它修復了我的問題:)!只是一個細節,我不得不在setOnFailed命令中添加一個轉換異常:Exception ex =(Exception)task.getException();非常感謝你! –

+0

啊,是的,'getException()'返回一個'Throwable'。更新的答案(您可能仍然需要轉換才能將其傳遞給您的'getExceptionDialog(...)'方法)。 –

+0

還需要演員:)。我想知道,在我原來的帖子中,我如何阻止FX線程?我認爲任務對象在那裏以避免這種情況。 –