Home » Java » TornadoFX, Kotlin: Bind label text value to String property of external file

TornadoFX, Kotlin: Bind label text value to String property of external file

Posted by: admin August 11, 2018 Leave a comment

Questions:

I have an external text file that I want to bind to a label so that when the external file value is modified, my UI auto-updates the string value.

So far, I have tried:

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

And in my borderpane, I reference the testid

label.bind(testid)

This reads the file successfully, but the testid doesn’t auto update its value when I edit the test file. I thought to try using a Handler() to force the variable to update the value every second, but I’m sure there’s a smarter way to use Properties and .observable() to bind the file and Property together.

EDIT:

Following on from mipa’s suggestion to use nio2, I’m having trouble producing the object/class for the timer:

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()
            }
        }
    }

How do I call this object to run – it’s currently resting inside my View() class which is being called by TornadoFX to produce the view, so I can’t call DirectWatcher.main(). Do I place a call to this object from within the other App class? I’m very lost.

Answers: