【问题标题】:Updating JavaFX Controls While Running the App在运行应用程序时更新 JavaFX 控件
【发布时间】:2017-03-07 21:49:44
【问题描述】:

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

这是我为从 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 

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

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

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

【问题讨论】:

    标签: java javafx javafx-2 javafx-8


    【解决方案1】:

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

    也许还有其他一些问题。


    作为一个整体的方法,你定义一个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();
    

    【讨论】:

    • 谢谢我通过这个例子明白了。现在有了更清晰的想法。
    猜你喜欢
    • 2015-12-04
    • 1970-01-01
    • 2015-03-06
    • 2021-01-20
    • 2011-05-12
    • 1970-01-01
    • 2013-09-21
    • 2019-08-31
    • 2013-09-22
    相关资源
    最近更新 更多