【发布时间】:2015-09-11 09:59:58
【问题描述】:
我正在寻找一个示例,以使用 Java8 u40 的新类 TextFormatter 将用户输入限制为仅数字和小数点。
http://download.java.net/jdk9/jfxdocs/javafx/scene/control/TextFormatter.Change.html
【问题讨论】:
我正在寻找一个示例,以使用 Java8 u40 的新类 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)。
【讨论】: