Share the post "Allow MaskFormatter To Accept Empty Value In Java"
One of the frustrating things in using the MaskFormatter class is that when the JFormattedTextField has an existing value, you cannot replace it with an empty value or set it to null. Wouldn’t it be nice if we could just set a property on the mask formatter to allow this, such as MaskFormatter.setAllowBlankField(true) perhaps?
Luckily, R.J. Lorimer wrote a custom class that inherited the MaskFormatter class to allow empty values to be set. Thank you R.J., your class saved me a great deal of time to create my own custom class! 😉
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
import java.text.ParseException; import javax.swing.text.MaskFormatter; public class AllowBlankMaskFormatter extends MaskFormatter { private boolean allowBlankField = true; private String blankRepresentation; public AllowBlankMaskFormatter() { super(); } public AllowBlankMaskFormatter(String mask) throws ParseException { super(mask); } public void setAllowBlankField(boolean allowBlankField) { this.allowBlankField = allowBlankField; } public boolean isAllowBlankField() { return allowBlankField; } /** * Update our blank representation whenever the mask is updated. */ @Override public void setMask(String mask) throws ParseException { super.setMask(mask); updateBlankRepresentation(); } /** * Update our blank representation whenever the mask is updated. */ @Override public void setPlaceholderCharacter(char placeholder) { super.setPlaceholderCharacter(placeholder); updateBlankRepresentation(); } /** * Override the stringToValue method to check the blank representation. */ @Override public Object stringToValue(String value) throws ParseException { Object result = value; if (isAllowBlankField() && blankRepresentation != null && blankRepresentation.equals(value)) { // an empty field should have a 'null' value. result = null; } else { result = super.stringToValue(value); } return result; } private void updateBlankRepresentation() { try { // calling valueToString on the parent class with a null attribute will get the 'blank' // representation. blankRepresentation = valueToString(null); } catch(ParseException e) { blankRepresentation = null; } } } |