edvin / tornadofx

Lightweight JavaFX Framework for Kotlin
Apache License 2.0
3.68k stars 272 forks source link

A custom double textfield #1341

Open AIGLEZMA opened 3 years ago

AIGLEZMA commented 3 years ago

Hey, i'm new to JavaFX and TornadoFX so i have some questions:

I want to make a double only textfield and bind it to a double property and i want to know how to:

zentox commented 3 years ago

Make the textfield only accept doubles to prevent the java.lang.NumberFormatException Accept , as a decimal separator

You can use a TextFormatter .

Accept the - char and do not throw java.lang.NumberFormatException

You probably have to specify a double value for it. Maybe use something as dummy value e.g. Double.NaN

Make the textfield show nothing by default (cause when you bind it to a double property it will show 0 by default)

You can override the NumberStringConverter toString method in order to achieve this.

Minimal example code:

        val textField = TextField()
        textField.textFormatter = ...
        val doubleProperty = SimpleDoubleProperty(0.0)
        val converter = ...
        Bindings.bindBidirectional(textField.textProperty(), doubleProperty, converter)
SchweinchenFuntik commented 3 years ago
val doubleProperty = doubleProperty(0.0)
textfield(doubleProperty).validator {
    if (it?.toDoubleOrNull() == null) error("Not correct Double Number")
    else success() // or null
}