[英]Binding `FXTask` message to `Label` without component coupling in TornadoFX
美好的一天。 我想知道是否有方便或简化的方式将FXTask
的messageProperty
和runningProperty
到Label
的textProperty
和visibleWhen
属性,而不将FXTask
和Label
本身耦合FXTask
?
例如,在下面的示例应用程序中,我通过将label的引用耦合到任务来绑定messageProperty
,该任务引入了额外的lateinit var statusLabel
。 类似地,我通过将task的引用耦合到引入额外val task
的标签来绑定runningProperty
。
class DummyView : View("Dummy View") {
override val root = vbox {
lateinit var statusLabel: Label
val task = object : Task<Void>() {
public override fun call(): Void? {
Platform.runLater { statusLabel.textProperty().bind(messageProperty()) } // label coupling
updateMessage("Initializing task...")
(1..3).forEach {
Thread.sleep(1000)
updateMessage("Doing task: $it...")
}
Thread.sleep(1000)
updateMessage("Task done")
Thread.sleep(1000)
return null
}
}
button("Do task") {
action {
Thread(task).apply {// task coupling
isDaemon = true
}.start()
}
}
statusLabel = label("Status") {
visibleWhen(task.runningProperty()) // task coupling
}
}
}
class DummyApp : App(DummyView::class)
有一个TaskStatus
对象可以传递给runAsync
。 该对象具有您正在运行的任务的所有有趣的属性。 也不需要将Task
子类化
class DummyView : View("Dummy View") {
val taskStatus = TaskStatus()
override val root = vbox {
button("Do task") {
action {
runAsync(taskStatus) {
updateMessage("Initializing task...")
(1..3).forEach {
Thread.sleep(1000)
updateMessage("Doing task: $it...")
}
Thread.sleep(1000)
updateMessage("Task done")
Thread.sleep(1000)
}
}
}
label(taskStatus.message) {
visibleWhen(taskStatus.running)
}
}
}
您甚至可以通过注入自动使用taskStatus。 如果不将TaskStatus的特定实例传递给runAsync,则将获得默认实例。 因此,这也适用:(区别是已注入TaskStatus,并且没有TaskStatus的实例传递给runAsync)
class DummyView : View("Dummy View") {
val taskStatus: TaskStatus by inject()
override val root = vbox {
button("Do task") {
action {
runAsync {
updateMessage("Initializing task...")
(1..3).forEach {
Thread.sleep(1000)
updateMessage("Doing task: $it...")
}
Thread.sleep(1000)
updateMessage("Task done")
Thread.sleep(1000)
}
}
}
label(taskStatus.message) {
visibleWhen(taskStatus.running)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.