Skip to content

Commit

Permalink
Add blur actions
Browse files Browse the repository at this point in the history
  • Loading branch information
ruckustboom committed Sep 30, 2022
1 parent ee8827e commit 3b7cfc8
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/main/kotlin/TextFields.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,22 @@ import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import javafx.util.StringConverter

public fun <T> TextField.editorFor(property: Property<T>, converter: StringConverter<T>) {
public enum class BlurAction { COMMIT, RESET, NONE }

public fun <T> TextField.editorFor(
property: Property<T>,
converter: StringConverter<T>,
onBlur: BlurAction = BlurAction.COMMIT,
) {
property.addAndRunListener { refresh(property, converter) }
focusedProperty().addListener { _, wasFocused, isFocused ->
if (!isFocused && wasFocused) update(property, converter)
when (onBlur) {
BlurAction.COMMIT -> focusedProperty().addListener { _, wasFocused, isFocused ->
if (!isFocused && wasFocused) update(property, converter)
}
BlurAction.RESET -> focusedProperty().addListener { _, wasFocused, isFocused ->
if (!isFocused && wasFocused) refresh(property, converter)
}
BlurAction.NONE -> Unit
}
addEventHandler(KeyEvent.KEY_PRESSED) {
when (it?.code) {
Expand Down Expand Up @@ -50,6 +62,8 @@ public fun TextField.editorFor(property: DoubleProperty, converter: StringConver
editorFor(property as Property<Double>, converter)
}

// Impl

private fun <T> TextField.update(property: Property<T>, converter: StringConverter<T>) {
try {
property.value = converter.fromString(text)
Expand Down

0 comments on commit 3b7cfc8

Please sign in to comment.