I want to limit the number of characters a control supports TextField
and I have tried this method:
public static void fijarTamañoMáximo(final TextField campoTexto, final int tamañoMáximo) {
campoTexto.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(final ObservableValue<? extends String> ov, final String valorAnterior, final String valorActual) {
Pattern permitido = Pattern.compile("[A-Za-zÑÇÁÉÍÓÚÀÈÌÒÙÏÜÂÊÎÔÛñçáéíóúàèìòùïüâêîôû]");
Matcher mpermitido = permitido.matcher(valorActual.substring(valorActual.length() - 1));
if (mpermitido.find()) {
if (campoTexto.getText().length() > tamañoMáximo) {
String s = campoTexto.getText().substring(0, tamañoMáximo);
campoTexto.setText(s);
}
} else // caracter no permitido, borrarlo
if (valorActual.length() == 1) {
campoTexto.setText(""); // ¿Por qué sale error?
} else {
campoTexto.setText(valorAnterior);
}
}
});
}
fijarTamañoMáximo(miTextField, 10); // limito a 10 caracteres
I also limit the data type to alphabetic characters. Up to here everything works fine (although I accept suggestions to improve it). The problem is that when the first character is typed as one that is not allowed, for example a number, an error comes out when I put the text of the TextField
a "" with campoTexto.setText("");
. The same thing happens if I try to delete the single character from the control and I don't know why.
Uses:
campoTexto.lengthProperty()
instead of :
and uses the same listener,
ChangeListener
to validate the number of characters allowed.Example:
In this way we can validate our
TextField
,CustomTextField
, etc, to avoid entering more than a certain number of characters.The problem that I have found in the previous answers is that if the illegal character is entered at the beginning or in the middle of the string then it does not work and allows the wrong character to be entered. To solve it we can go through all the characters of the new string and check one by one if it meets the filter:
The error occurs because when an illegal character is typed being the length of
TextField
0 in the declaration of theMatcher
attempt to assign a substring(-1). On the other hand, when the text "" is assigned toTextField
it causes an automatic refill of the Listener that returns to encounter the same error from the beginning. The solution is to not apply thePattern
if nothing has been added to theTextField
:For those who prefer to use
lengthProperty
:Solution a little longer but just as effective.