我正在寻找一个使用Java8 u40的新类TextFormatter
将用户输入限制为仅数字和小数点的示例。
http://download.java.net/jdk9/jfxdocs/javafx/scene/control/TextFormatter.Change.html
答案 0 :(得分:18)
请看这个例子:
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)。