Java 8 U40 TextFormatter(JavaFX)仅限用于十进制数的用户输入 [英] Java 8 U40 TextFormatter (JavaFX) to restrict user input only for decimal number
问题描述
我正在寻找一个示例,使用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过滤器)构造函数,它仅将过滤器作为参数。
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)仅限用于十进制数的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!