I have a JFormattedTextField using the following mask formatter:
private MaskFormatter maskForInput;
maskForInput=new MaskFormatter("####"); // I have tried using stars (*) too.
maskForInput.setValidCharacters("0123456789");
javax.swing.JFormattedTextField playerRaiseField=new javax.swing.JFormattedTextField(maskForInput);
This is supposed to allow the user to enter up to 4 digits as an input. However when I am trying to Integer.parseInt(playerRaiseField.getText()) the String returned from this field I am always getting a NumberFormatException possibly due to the empty spaces left on user input.
To clear this up:
If the user inputs 560 for example there is a trailing space left behind so the String I am reading is 560( ) and when trying to parse this String into an int this exception is thrown. Any workarounds? How can I modify the mask formatter to accept 1 to 4 digits and not always 4 digits fixed??
Note: Curiously enough using trim() on the String returned is still not removing the extra whitespace character…
There are a number of things wrong with your expectations…
Firstly, you seem to believe that a formatted field can have any number of characters. This isn’t true (while you can get the text, the field remains in what it considers to be an invalid state). The formatted field expects that the all the places of the mask must be filled.
Secondly, you should be using the
JFormattedTextField#getValuemethod to return the value of the field, notgetTextThirdly, the text being returned is filled with the mask’s placeholder character (
MaskFormatter#getPlaceholder), which may or may not be a space, soString#trimprobably isn’t going to be of help…If you want the user to only be able to enter a numeric value, which may consist of 0-n characters, then you really should consider using a
DocumentFilterapplied to normalJTextField