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; } })); 
Sign up to request clarification or add additional context in comments.

5 Comments

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?
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?
Yes, It did. Thanks again for your follow up on my comments.
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
What would be the pattern to accept negative decimal numbers as well?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.