All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dankito.utils.javafx.ui.controls.NumberTextFieldBase.kt Maven / Gradle / Ivy

There is a newer version: 1.0.9
Show newest version
package net.dankito.utils.javafx.ui.controls

import javafx.beans.value.ObservableValue
import javafx.scene.control.TextField
import javafx.util.StringConverter
import tornadofx.bind


abstract class NumberTextFieldBase(propertyToBind: ObservableValue? = null) : TextField() {


    protected abstract fun isTextInputAllowed(text: String): Boolean

    protected abstract fun convertToString(value: Number): String

    protected abstract fun convertFromString(value: String): Number?



    init {
        textProperty().addListener { _, oldValue, newValue ->
            if (isTextInputAllowed(newValue) == false) {
                this.text = oldValue
            }
        }

        bind(propertyToBind)
    }

    protected fun bind(propertyToBind: ObservableValue?) {
        propertyToBind?.let {
            bind(propertyToBind, false, createStringConverter(), null)
        }
    }


    protected open fun createStringConverter(): StringConverter {
        return object : StringConverter() {
            override fun toString(value: Number): String {
                return convertToString(value)
            }

            override fun fromString(value: String): Number? {
                return convertFromString(value)
            }

        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy