运行 应用程序更新 JavaFX 控件

Updating JavaFX Controls While Running the App

我正在使用 JavaFx 创建 Java 独立应用程序。 我看过一些示例,但我无法理解如何在我的代码场景中使用 javaFX Task

这是我为从 SceneBuilder 设置的 Button 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 

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

现在我在同一个函数中逐步更新多个控件,随着代码的逐步进行,但最后在执行完成时更新。

我想在执行时更新控件,如代码所示。

这可能是其他问题的重复:

  • JavaFx: Update UI label asynchronously with messages while application different methods execution
  • JavaFx ProgressBar doesnt update
  • Platform.runLater and Task in JavaFX
  • Usage of JavaFX Platform.runLater and access to UI from a different thread

也许还有一些其他问题。


作为一种整体方法,您定义一个任务,然后在任务的执行体中,您利用 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();