I am working with a JavaFX 2.2 project and I have a problem using the TextField control. I want to limit the characters that users will enter to each TextField but I can't find a property or something like maxlength. The same problem was existing to swing and was solved with this way. How to solve it for JavaFX 2.2?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
I'm using a simpler way to both limit the number of characters and force numeric input:
The code below will re-position the cursor so the user doesn't accidentally overwrite their input.
The full code i used to solve my problem is the code below. I extend the TextField class like Sergey Grinev done and i added an empty constructor. To set the maxlength i added a setter method. I first check and then replace the text in the TextField because i want to disable inserting more than maxlength characters, otherwise the maxlength + 1 character will be inserted at the end of the TextField and the first charcter of the TextField will be deleted.
Inside the fxml file i added the import (of the package that the TextFieldLimited class is existing) on the top of the file and replace the TextField tag with the custom TextFieldLimited.
Inside the controller class,
on the top (property declaration),
@FXML
private TextFieldLimited usernameTxtField;
inside the initialize method,
usernameTxtField.setLimit(40);
That's all.
You can do something similar to approach described here: http://fxexperience.com/2012/02/restricting-input-on-a-textfield/
With java8u40 we got a new class TextFormatter: one of its main responsibilities is to provide a hook into any change of text input before it gets comitted to the content. In that hook we can accept/reject or even change the proposed change.
The requirement solved in the OP's self-answer is
Using a TextFormatter, this could be implemented like:
Asides:
I have this bit of code that only allows numbers and limits the input length on a text field in Javafx.