You can use trim () in your String to remove left and right empty spaces from the value:
String str = formattedTextField.getText().trim();
Another way, maybe even better by giving you more control of what is typed, is by using the PlainDocument . With it, you not only control the number of characters you enter, but also just numbers:
class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
@Override
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
if (str == null) {
return;
}
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str.replaceAll("\D++", ""), attr);
}
}
}
Then just apply to any JTextfield
:
JTextFieldLimit limitDocument = new JTextFieldLimit(3);
seuTextField.setDocument(limitDocument);
The signature of the insertString
method receives three parameters:
-
int offset
= indicates in which index of the current string of the field, the new one will be added;
-
String str
= is the new string to be added (digits in your case);
-
AttributeSet attr
= are attributes of the string (like type, size and font style, etc ...), in this case, it did not make any difference.
No str.replaceAll("\D++", "")
, I'm passing a Regular Expression that will remove any characters passed in the string other than digits.
Remembering that the constructor of class JTextFieldLimit
receives the limit of characters that its field can have, and this class can be used in any field of text.
Note: With the class shown above, you do not need to use
MaskFormatter
and nor JTextFormatterField
.
References:
Limit JTextField input to a maximum length (java2s)
How to implement in Java (JTextField class) to allow entering only digits?
Limiting the number of characters in a JTextField