PeptideWitch
PeptideWitch

Reputation: 2349

Bind label text value to String property of external file

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.

Upvotes: 0

Views: 883

Answers (1)

mipa
mipa

Reputation: 10650

There is no built-in mechanism in JavaFX which would allow such a binding but you can use the Java watch service as described here: http://www.baeldung.com/java-nio2-watchservice The Oracle doc can be found here: https://docs.oracle.com/javase/10/docs/api/java/nio/file/WatchService.html

Upvotes: 2

Related Questions