代码之家  ›  专栏  ›  技术社区  ›  PeptideWitch

TornadoFX,Kotlin:将标签文本值绑定到外部文件的字符串属性

  •  0
  • PeptideWitch  · 技术社区  · 8 年前

    我有一个外部文本文件,我想绑定到一个标签,这样当外部文件值被修改时,我的UI会自动更新字符串值。

    到目前为止,我已经尝试过:

    val testid: ObservableStringValue = SimpleStringProperty(File("src/.../test").readText())
    

    在我的边界窗格中,我引用了testid

    label.bind(testid)
    

    这会成功读取文件,但编辑测试文件时testid不会自动更新其值。我想尝试使用Handler()强制变量每秒更新一次值,但我相信有一种更聪明的方法来使用属性和属性。observable()将文件和属性绑定在一起。

    编辑:

    根据mipa关于使用nio2的建议,我很难为计时器生成对象/类:

    object DirectoryWatcher {
    
        @JvmStatic  fun main(args:Array<String>) {
        val watchService = FileSystems.getDefault().newWatchService()
        val path = Paths.get(System.getProperty("src/pykotinterface/test"))
    
        path.register(
        watchService,
        StandardWatchEventKinds.ENTRY_CREATE,
        StandardWatchEventKinds.ENTRY_DELETE,
        StandardWatchEventKinds.ENTRY_MODIFY)
    
        val key:WatchKey = watchService.take()
        while (key != null) {
        for (event in key.pollEvents()) {
        println(
                "Event kind:" + event.kind()
                + ". File affected: " + event.context() + ".")
                }
        key.reset()
                }
            }
        }
    

    如何调用该对象来运行——它当前位于我的View()类中,TornadFX正在调用该类来生成视图,因此我无法调用DirectWatcher。main()。我是否从其他应用程序类中调用此对象?我很迷路。

    1 回复  |  直到 6 年前
        1
  •  2
  •   mipa    8 年前

    JavaFX中没有允许这种绑定的内置机制,但您可以使用如下所述的Java watch服务: http://www.baeldung.com/java-nio2-watchservice Oracle文档可以在以下位置找到: https://docs.oracle.com/javase/10/docs/api/java/nio/file/WatchService.html

    推荐文章