Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 720
Moe Avatar asked Jun 25 '15 00:06

Moe


1 Answers

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;
    }
}));
  • Here I used the TextFormatter(UnaryOperator filter) constructor which takes a filter only as a parameter.

  • To understand the if-statement refer to DecimalFormat parse(String text, ParsePosition pos).

like image 142
Uluk Biy Avatar answered Nov 12 '22 19:11

Uluk Biy