栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaFx:在执行应用程序不同方法时,与消息异步更新UI标签

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaFx:在执行应用程序不同方法时,与消息异步更新UI标签

您可以在JavaFX应用程序线程之外(在Task中)运行耗时的方法。任务中具有特殊的API,可轻松提供状态消息,这些消息可以在绑定的标签中显示。

我对以下代码所做的工作是尝试创建一个模拟您在问题中提供的建议流程和消息报告的系统。由于代码中记录的各种原因,用户只能看到一些消息。

import javafx.concurrent.Task;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.stage.*;import javafx.application.*;public class MessagingDemo extends Application {  public void start(Stage stage) {    // "message1" won’t be seen because we perform the next action on the JavaFX     // application thread then update the label text again without releasing the     // thread to the JavaFX system.    Label label = new Label("message1");    label.setPrefWidth(300);    // some action    // "action done" won’t be seen because we set text again in the next statement.    label.setText("action done");    // you're not going to see this because we immediately bind text to the task text and launch the task.     label.text("calling method.. wait for some time")    Task <Void> task = new Task<Void>() {      @Override public Void call() throws InterruptedException {        // "message2" time consuming method (this message will be seen).        updateMessage("message2");        // some actions        Thread.sleep(3000);        // "message3" time consuming method (this message will be seen).        updateMessage("message3");        //more  time consuming actions        Thread.sleep(7000);        // this will never be actually be seen because we also set a message         // in the task::setonSucceeded handler.        updateMessage("time consuming method is done with success");        return null;      }    };    label.textProperty().bind(task.messageProperty());    // java 8 construct, replace with java 7 pre if using java 7.    task.setonSucceeded(e -> {      label.textProperty().unbind();      // this message will be seen.      label.setText("operation completed successfully");    });    Thread thread = new Thread(task);    thread.setDaemon(true);    thread.start();    stage.setScene(new Scene(label));    stage.show();  }  public static void main(String args[]) {    launch(args);  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/507387.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号