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
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).
5 Comments
Moe
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?
Uluk Biy
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?
Moe
Yes, It did. Thanks again for your follow up on my comments.
David Fisher
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
golimar
What would be the pattern to accept negative decimal numbers as well?