I need to restrict input into a TextField to integers. Any advice?
相关问题
- I get an exception when trying to swap elements in
- JFX scale image up and down to parent
- Dragging an undecorated Stage in JavaFX
- Jasper: error opening input stream from url
- is it normal for image inputs to be omitted from t
相关文章
- 放在input的text下文本一直出现一个/(即使还没输入任何值)是什么情况
- Show a different value from an input that what wil
- Is there a way to hide the new HTML5 spinbox contr
- Programmatically interrupting raw_input
- Low quality icon in taskbar of a Stage. JavaFX
- Bootstrap input field inside tooltip popover remov
- Loading custom font using JavaFX 8 and css
- ValueError: too many values to unpack (expected 2)
This is what I use:
The same in lambda notation would be:
I would like to improve Evan Knowles answer: https://stackoverflow.com/a/30796829/2628125
In my case I had class with handlers for UI Component part. Initialization:
And the numbericSanitization method:
Keyword synchronized is added to prevent possible render lock issue in javafx if setText will be called before old one is finished execution. It is easy to reproduce if you will start typing wrong chars really fast.
Another advantage is that you keep only one pattern to match and just do rollback. It is better because you can easily abstragate solution for different sanitization patterns.
The
TextInput
has aTextFormatter
which can be used to format, convert and limit the types of text that can be input.The
TextFormatter
has a filter which can be used to reject input. We need to set this to reject anything that's not a valid integer. It also has a converter which we need to set to convert the string value to an integer value which we can bind later on.Lets create a reusable filter:
The filter can do one of three things, it can return the change unmodified to accept it as it is, it can alter the change in some way it deems fit or it can return
null
to reject the change all together.We will use the standard
IntegerStringConverter
as a converter.Putting it all together we have:
If you want don't need a reusable filter you can do this fancy one-liner instead:
This works fine as it allows you to enter only integer value and decimal value (having ASCII code 46).