Java 8 U40 TextFormatter(JavaFX)仅限用于十进制数

时间:2015-06-25 00:46:01

标签: javafx java-8 javafx-8

我正在寻找一个使用Java8 u40的新类TextFormatter将用户输入限制为仅数字和小数点的示例。 http://download.java.net/jdk9/jfxdocs/javafx/scene/control/TextFormatter.Change.html

1 个答案:

答案 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;
    }
}));
相关问题