Skip to content

Ktfx Commons – Threads

Hendra Anggrian edited this page Nov 21, 2019 · 2 revisions

Scope functions

Taking clue from Kotlin Scope Functions, Ktfx provides similar API to execute a block of code in JavaFX application thread at unspecified near-future.

runLater

Unlike kotlin.run, ktfx.runLater does not expect return type, simply because the code is executed later.

// without receiver
ktfx.runLater {
    doSomethingInFxThread()
}

// with receiver
val field = TextField()
field.runLater {
    requestFocus()
}

withLater

Like ktfx.runLater, but accepts receiver as function parameter.

val button = Button("OK")
withLater(button) {
    fire()
}

applyLater

Executing the code block later while returning the object of the receiver.

val dialog = Alert(AlertType.WARNING, "Are you sure?").applyLater {
    showAndWait()
}

alsoLater

Like ktfx.applyLater, but moved receiver to function type parameter.

val label = Label().alsoLater {
    it.textProperty().bindBidirectional(otherLabel.textProperty())
}

letLater

Like ktfx.runLater, but moved receiver to function type parameter.

val hyperlink = Hyperlink()
hyperlink.letLater {
    it.style = "-fx-text-inner-color: red;"
    it.applyCss()
}

Checking thread & features

Simply run ktfx.isFxThread() to determines whether or not the calling thread is the JavaFX application thread.

runLater {
    doSomething()
    isFxThread() // is always true
}

Checking a feature is available directly from ConditionalFeature.

if (ConditionalFeature.INPUT_TOUCH.isSupported()) {
    doSomething()
}