2017-03-07 75 views
0

我使用JavaFX創建一個Java獨立應用程序。 我已經看到了一些例子,但我無法理解如何使用JavaFX的Task在我的代碼的情況。更新JavaFX的控制,同時運行的應用程序

這是我要求我從SceneBuilder設置按鈕的OnAction控制器功能 - >

public class MainScreenController { 
    @FXML 
    private JFXButton btnSelectImg; 
    @FXML 
    private ImageView imageViewObj; 
    @FXML 
    private ProgressBar progressBarObj; 
//.. 
//.. 
    @FXML 
    private void onFileSelectButtonClick() { 
     //Some Operations are carried out 
     //.. 
     //Then I want to set Image in ImageView 
     imageViewObj.setImage(myImage); 

     // Some Code Here 
     //.. 

     // Set Progress 
     progressBarObj.setProgress(0.1); 

     // Some Code Here 
     //.. 

     // Set Progress 
     progressBarObj.setProgress(0.2); 

     //... 
     //... 

     // Maybe change some other Controls 

     //.......... 
    } 
    //.. 
//.. 
} 

現在在這裏,我在同一個功能逐漸更新多個控件的代碼進步一步但是當執行完成後它會被更新。

我想更新而執行如圖所示的代碼中的控件。

回答

2

這是其他問題位的可能重複:

也許還有一些其他問題。


作爲一個整體的方法,你定義一個任務,然後將任務執行體內,你利用Platform.runLater()的UpdateProgress()和其他機制來實現你所需要的。有關這些機制的進一步解釋,請參閱相關問題。

final ImageView imageViewObj = new ImageView(); 
Task<Void> task = new Task<Void>() { 
    @Override protected Void call() throws Exception { 
     //Some Operations are carried out 
     //.. 

     //Then I want to set Image in ImageView 
     // use Platform.runLater() 
     Platform.runLater(() -> imageViewObj.setImage(myImage)); 

     // Some Code Here 
     //.. 

     // Set Progress 
     updateProgress(0.1, 1); 

     // Some Code Here 
     //.. 

     // Set Progress 
     updateProgress(0.2, 1); 

     int variable = 2; 
     final int immutable = variable; 

     // Maybe change some other Controls 
     // run whatever block that updates the controls within a Platform.runLater block. 
     Platform.runLater(() -> { 
      // execute the control update logic here... 
      // be careful of updating control state based upon mutable data in the task thread. 
      // instead only use immutable data within the runLater block (avoids race conditions). 
     }); 

     variable++; 

     // some more logic related to the changing variable. 

     return null; 
    } 
}; 

ProgressBar updProg = new ProgressBar(); 
updProg.progressProperty().bind(task.progressProperty()); 

Thread thread = new Thread(task, "my-important-stuff-thread"); 
thread.setDaemon(true); 
thread.start(); 
+0

謝謝我通過這個例子瞭解它。現在更清晰的想法。 –

相關問題