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.