As you are doing, no mask is being applied to the field. You are only initiating the variable mskQuantia
, but without any valid mask.
The method setValidCharacters()
only filters what you want to be accepted in the mask applied in the field, hence we return to the previous paragraph, you are not applying any mask, even though you are "installing" MaskFormatter
empty in the field. >
This answer about how to do this restriction in JTextField may be the most recommended option for the case you want , since there is less compromise with mask or formatting than must be typed.
Just adapt the code by removing the maximum quantity limitation of characters:
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());