运行应用程序时更新JavaFX控件

时间:2017-03-07 21:49:44

标签: java javafx javafx-2 javafx-8

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

这是我调用Button onAction的Controller函数,我从SceneBuilder设置了这个函数 - >

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 

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

现在我在这里逐步更新同一个函数中的多个控件,因为代码会逐步进行,但是在执行完毕后它会立即更新。

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

1 个答案:

答案 0 :(得分:2)

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

也许还有其他一些问题。

作为一种整体方法,您定义一个Task,然后在Task的执行体内,您可以使用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();