问题描述
我正在寻找一个示例,使用 Java8 u40 的新类 TextFormatter
将用户输入限制为仅数字和小数点.http://download.java.net/jdk9/jfxdocs/javafx/scene/control/TextFormatter.Change.html
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
推荐答案
请看这个例子:
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) 构造函数,只将过滤器作为参数.
Here I used the TextFormatter(UnaryOperator filter) constructor which takes a filter only as a parameter.
要了解 if 语句,请参阅 DecimalFormat parse(String text, ParsePosition pos).
To understand the if-statement refer to DecimalFormat parse(String text, ParsePosition pos).
这篇关于Java 8 U40 TextFormatter (JavaFX) 限制用户仅输入十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!