As you are doing, no masks are being applied in the field. You are just starting the variable mskQuantia
, but without any valid mask.
The method setValidCharacters()
just filter what you want to be accepted in the mask applied in the field, then we return to the previous paragraph, you are not applying any mask, despite being "installing" the MaskFormatter
empty in the field.
This answer on how to do this restriction in Jtextfield may be the most recommended option for the case you want, since there is not so much commitment to mask or formatting what should be typed.
Simply adapt the code by removing the maximum number of characters limitation:
import javax.swing.text.PlainDocument;
class JTextFieldFilter extends PlainDocument {
JTextFieldLimit() {
super();
}
@Override
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
if (str == null) {
return;
}
super.insertString(offset, str.replaceAll("\\D++", ""), attr);
}
}
The above Code should be applied to JTextField
as follows:
seuJTextField.setDocument(new JTextFieldFilter());
Why didn’t you apply any mask.
– user28595
It’s because in fact, I don’t want to apply mask to limit the digits (for example
###
), I just want the field to accept numbers, no limits ...– Daniel Santos