JavaFX 2 StringProperty在封闭方法返回之前不会更新字段 [英] JavaFX 2 StringProperty does not update field until enclosing method returns

查看:82
本文介绍了JavaFX 2 StringProperty在封闭方法返回之前不会更新字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JavaFX应用程序中更新Label,以便在方法运行时文本会多次更改:

I would like to update a Label in a JavaFX application so that the text changes multiple times as the method runs:

private void analyze(){
    labelString.setValue("Analyzing"); // (labelString is bound to the Label during initialization)
    // <Some time consuming task here>
    labelString.setValue("Analysis complete!");
}

但是当我运行它时,标签在任务完成之前不会更新,并只显示之前的任何内容,直到 analyze()方法返回。

But when I run this, the label does not update until the task finishes, and just displays whatever it was before until the analyze() method returns.

如何强制更新标签,使其在开头显示分析,然后分析完成!当任务完成后?

How can I force update the label so that it will show "Analyzing" in the beginning followed by "Analysis complete!" when the task is complete?

推荐答案

假设你正在调用你的 analyze() FX应用程序线程上的方法(例如在事件处理程序中),耗时的代码阻塞该线程并阻止UI更新,直到完成为止。正如@ glen3b在评论中所说,你需要使用外部线程来管理这段代码。

Assuming you are invoking your analyze() method on the FX Application Thread (e.g. in an event handler), your time consuming code is blocking that thread and preventing the UI from updating until it is complete. As @glen3b says in the comments, you need to use an external thread to manage this code.

JavaFX提供了一个任务API 可以帮助您完成此任务。特别是,它提供了为您调用Java FX Application线程上的代码的方法,允许您从后台安全地更新UI 任务

JavaFX provides a Task API which helps you do this. In particular, it provides methods which invoke code on the Java FX Application thread for you, allowing you to update the UI safely from your background Task.

所以你可以这样做

private void analyze() {
    Task<Void> task = new Task<Void>() {
        public Void call() {
            updateMessage("Analyzing");
            // time consuming task here
            updateMessage("Analysis complete");
        }
    };
    labelString.bind(task.messageProperty());
    new Thread(task).start();
}

如果你需要解除绑定 StringProperty 任务完成后,您可以

If you need to unbind the StringProperty when the task is complete, you can do

task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
    @Override
    public void handle(WorkerStateEvent event) {
        labelString.unbind();
    }
});

这篇关于JavaFX 2 StringProperty在封闭方法返回之前不会更新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆