【问题标题】:TornadoFX: Error while updating label inside runAsyncTornadoFX:更新 runAsync 中的标签时出错
【发布时间】:2020-06-17 17:10:26
【问题描述】:

我尝试使用 Kotlin 和 TornadoFX 库中的套接字连接来实现一个聊天应用程序来制作 GUI。 当我尝试启动客户端时出现问题,因为它一直在等待来自服务器的消息,尽管我将更新标签并接收消息的代码放在 runAsync 中。我红色了 TornadoFX 文档并观看了 youtube 视频,但我无法找到解决方案。 我知道问题是程序卡在那个块中,但不知道该怎么做。

    class MyFirstView: View("Chat"){

        var input: TextField by singleAssign()
        var test = SimpleStringProperty()
        val client: Client by inject()

        init {
            client.connect()
            val t = thread(true) {
                 while (true) {
                      random = client.getMessage()
                      println(random)
                      Platform.runLater { test.set(random) }
                 }
            }
        }

        override val root = vbox {
            hbox {
                label(test) {
                    bind(test)
                }
            }
            hbox {
                label("Write here some text")
                input = textfield()
            }
            hbox {
                button("Send") {
                    action{
                        client.writer.println(input.text)
                    }
                }
            }
        }
    }

【问题讨论】:

    标签: kotlin tornadofx


    【解决方案1】:

    您只能在 UI 线程上更新 UI 元素,因此如果您想从后台线程操作 UI,您需要将该特定代码包装在 runLater { } 中。

    另一方面,您不应该操纵文本字段的文本或使用 singleAssign 存储 ui 元素引用。相反,您应该将文本字段绑定到 StringProperty 并改为操作该值。指南中对此进行了介绍,因此请查看:)

    【讨论】:

    • 我更新了我的代码并更改了构造函数,看起来效果很好。我在 init 块内添加了一个线程
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多