将标签文本值绑定到外部文件的String属性



我有一个外部文本文件,我想将其绑定到标签,以便在修改外部文件值时,我的UI会自动更新字符串值。

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

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

在我的borderpane中,我引用了测试的

label.bind(testid)

这成功地读取了文件,但当我编辑测试文件时,testid不会自动更新其值。我想尝试使用Handler((强制变量每秒更新一次值,但我相信有一种更聪明的方法可以使用Properties和.obsobservable((将文件和Property绑定在一起。

编辑:

根据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((类中,TornadoFX正在调用该类来生成视图,所以我不能调用DirectWatcher.main((。我要从其他应用程序类中调用这个对象吗?我很失落。

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

相关内容

最新更新