Interesting, as DateFormatter
seems to do almost all the tricks.
So why donβt you override its method, which does the final check and formatting to process all entered String
that are too short as empty String
.
DateFormatter dateFormatter = new DateFormatter(dateFormat) { @Override public Object stringToValue(String text) throws ParseException { if(!getFormattedTextField().hasFocus()) if (text.length() != 4) { return null; } return super.stringToValue(text); } };
EDIT:
As @nIcE cOw suggested, the easiest way to serve it is with focus:
final JFormattedTextField textField = new JFormattedTextField(dateFormatter); textField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { super.focusLost(e); if(textField.getText().length() != 4) textField.setText(""); } });
source share