You can use the Trim() in your String, to remove left and right empty spaces from the value:
String str = formattedTextField.getText().trim();
Another way, maybe it’s even better to give you more control than is typed, is by using the class Plaindocument. With it, you not only control the amount of characters you type, but you also want 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 method insertString
receives three parameters:
int offset
= indicates which index of the current string in the field, the new will be added;
String str
= is the new string that will be added (digits, in your case);
AttributeSet attr
= are attributes of the string(like font type, font size and style, etc...), in this case, it made no difference to us.
In the str.replaceAll("\\D++", "")
, I’m passing a Regular Expression that will remove any characters passed in the string that are not digits.
Remembering that the class builder JTextFieldLimit
receives the character limit your field may have, and this class can be used in any text field.
Obs.: With the class shown above, you don’t need to use or
MaskFormatter
and neither 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
Didn’t you want to leave the OOP question? I was answering
– Maniero