如何在javaFX中将更改侦听器添加到任务的消息属性



我正在使用JavaFX任务来执行耗时的代码,该代码在for循环中处理许多项目。 任务的进度由进度条指示,该进度条从 for 循环内部更新。 但是,除了进度条之外,我还有一些标签,这些标签指示要处理的项目总数和当前正在处理的项目的进度。 我试图将任务messageProperty绑定到标签textProperty,但是我有多个标签需要更新,messageProperty可以容纳单个String。 我考虑过用逗号分隔值字符串更新messageProperty,然后像这样拆分字符串

label1.textProperty().bind(task.messageProperty().toString().split(",")[0]);
label2.textProperty().bind(task.messageProperty().toString().split(",")[1]);
label3.textProperty().bind(task.messageProperty().toString().split(",")[2]);

但是我收到错误

The method bind(ObservableValue<? extends String>) in the type Property<String> is not applicable for the arguments (String)

所以我正在考虑向messageProperty添加一个ChangeListener并从ChangeListener内部更新标签

有人可以帮我确定哪种方法是最好的以及如何为messageProperty编写ChangeListener吗?

label1.textProperty.bind(Bindings.createStringBinding(
() -> task.getMessage().split(",")[0],
task.messageProperty());
//...

task.messageProperty().addListener((obs, oldMsg, newMsg) -> {
label1.setText(newMsg.split(",")[0]);
// ...
})

最新更新