13

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

1 Answer 1

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;
    }
}));
5
  • 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, 2015 at 18:18
  • 2
    There 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. And is this my post answers your question?
    – Uluk Biy
    Jun 26, 2015 at 5:09
  • Yes, It did. Thanks again for your follow up on my comments.
    – Moe
    Jun 26, 2015 at 13:47
  • 2
    The 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, stackoverflow.com/a/40472822/2331302 is a better answer Jul 24, 2020 at 13:28
  • What would be the pattern to accept negative decimal numbers as well?
    – golimar
    Feb 2, 2021 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.