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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With