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
private void registerListener1(TextField tf1, TextField tf2,TextField tf3,TextField tf4) {
tf1.textProperty().addListener((obs, oldText, newText) -> {
if(newText.length() == 12) {
tf1.setText(newText.substring(0, 3));
tf2.setText(newText.substring(tf1.getText().length(), 6));
tf3.setText(newText.substring(tf1.getText().length()+tf2.getText().length(), 9));
tf4.setText(newText.substring(tf1.getText().length()+tf2.getText().length()+tf3.getText().length()));
tf4.requestFocus();
}
});
}
private void registerListener(TextField tf1, TextField tf2) {
tf1.textProperty().addListener((obs, oldText, newText) -> {
if(oldText.length() < 3 && newText.length() >= 3) {
tf2.requestFocus();
}
});
}
The code below will re-position the cursor so the user doesn't accidentally overwrite their input.
public static void setTextLimit(TextField textField, int length) {
textField.setOnKeyTyped(event -> {
String string = textField.getText();
if (string.length() > length) {
textField.setText(string.substring(0, length));
textField.positionCaret(string.length());
}
});
}
You can do something similar to approach described here: http://fxexperience.com/2012/02/restricting-input-on-a-textfield/
class LimitedTextField extends TextField {
private final int limit;
public LimitedTextField(int limit) {
this.limit = limit;
}
@Override
public void replaceText(int start, int end, String text) {
super.replaceText(start, end, text);
verify();
}
@Override
public void replaceSelection(String text) {
super.replaceSelection(text);
verify();
}
private void verify() {
if (getText().length() > limit) {
setText(getText().substring(0, limit));
}
}
};