Java 8 U40 TextFormatter (JavaFX) 限制用户输入十进制数
Java 8 U40 TextFormatter (JavaFX) to restrict user input only for decimal number
我正在寻找一个示例,使用 Java8 u40 的新 class TextFormatter
将用户输入限制为仅数字和小数点。
http://download.java.net/jdk9/jfxdocs/javafx/scene/control/TextFormatter.Change.html
请看这个例子:
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;
}
}));
这里我使用了TextFormatter(UnaryOperator filter)构造函数,它只接受一个过滤器作为参数。
要了解 if 语句,请参阅 DecimalFormat parse(String text, ParsePosition pos)。
我正在寻找一个示例,使用 Java8 u40 的新 class TextFormatter
将用户输入限制为仅数字和小数点。
http://download.java.net/jdk9/jfxdocs/javafx/scene/control/TextFormatter.Change.html
请看这个例子:
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;
}
}));
这里我使用了TextFormatter(UnaryOperator filter)构造函数,它只接受一个过滤器作为参数。
要了解 if 语句,请参阅 DecimalFormat parse(String text, ParsePosition pos)。