Moe
Moe

Reputation: 1537

Java 8 U40 TextFormatter (JavaFX) to restrict user input only for decimal number

I am looking for an example to restrict user input to only digits and decimal points using the new class TextFormatter of Java8 u40. http://download.java.net/jdk9/jfxdocs/javafx/scene/control/TextFormatter.Change.html

Upvotes: 13

Views: 22615

Answers (1)

Uluk Biy
Uluk Biy

Reputation: 49215

Please see this example:

DecimalFormat format = new DecimalFormat( "#.0" );

TextField field = new TextField();
field.setTextFormatter( new TextFormatter<>(c ->
{
    if ( c.getControlNewText().isEmpty() )
    {
        return c;
    }

    ParsePosition parsePosition = new ParsePosition( 0 );
    Object object = format.parse( c.getControlNewText(), parsePosition );

    if ( object == null || parsePosition.getIndex() < c.getControlNewText().length() )
    {
        return null;
    }
    else
    {
        return c;
    }
}));

Upvotes: 23

Related Questions