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
            Asked
            
        
        
            Active
            
        
            Viewed 2.2k times
        
    1 Answers
23
            Please see this example:
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;
    }
}));
Here I used the TextFormatter(UnaryOperator filter) constructor which takes a filter only as a parameter.
To understand the if-statement refer to DecimalFormat parse(String text, ParsePosition pos).
        Uluk Biy
        
- 48,655
 - 13
 - 146
 - 153
 
- 
                    Any recommendation on books to read? I am still new to Java, and I need a little more explanation. I looked at "Java The Complete Reference Ninth Edition" but I found nothing related to this. I even couldn't find the usages of replaceText and replaceSelection in there. I am not sure if I am looking in the wrong place or not, where can I find some reading about the replaceText/Selection? – Moe Jun 25 '15 at 18:18
 - 
                    2There are separate books on JavaFX only. So first read a book on Java first then on JavaFX. If you know other programming languages like C/C++ or C#, you can easily learn Java as well. By the way, I didn't use replaceText/Selection in the answer but you are asking about it. It is bit out of context. Despite this see [this searches](http://stackoverflow.com/search?q=%5Bjavafx%5D+or+%5Bjavafx-2%5D+or+%5Bjavafx-8%5D+replacetext). And is this my post answers your question? – Uluk Biy Jun 26 '15 at 05:09
 - 
                    Yes, It did. Thanks again for your follow up on my comments. – Moe Jun 26 '15 at 13:47
 - 
                    2The formatters that come with java aren't very good for this sort of thing. For instance, I can't start typing with a leading negative sign but can go back and add it later. Because of this, https://stackoverflow.com/a/40472822/2331302 is a better answer – David Fisher Jul 24 '20 at 13:28
 - 
                    What would be the pattern to accept negative decimal numbers as well? – golimar Feb 02 '21 at 11:57