Skip to main content

DateFormattedFextField with control if the typed date is correct

No replies
anaq
Offline
Joined: 2006-04-04
Points: 0

Dear all,

I'm trying to make a DateFormattedTextField with "typing" control. This means when the user types a date in this textfield and a digit makes this date uncorrect, it will be not passed to the textfield. For example user tries to type 12.13.____ (dd.MM.yyyy), but the textfield stops him and the textfield contains only 12.1_.____.
This control is done in overriden method insertString in my own Document class. This works great on fields without maskformatter (I have such IntegerTextFields and FloatTextFields), but when I add a maskformatter, the method insertString is called only after focus events - not when typing. I have tried to add a DocumentFilter or an InputVerifier, but this didn't help me... I tried to use insertUpdate event from documentlistener, but the attempt to rewrite the bad date "12.13.____" with "12.1_.____" throws java.lang.IllegalStateException - Attempt to mutate in notification. DocumentEvent has no consume method like keyevents. Adding UndoableEditListener didn't help (undo event removes the bad '3' digit, but doesn't replace it with '_', double undo is not possible)

This example allows the user to type 12.13.2010, but after focus lost is this field cleared (replaced wiht "__.__.____"), because it's not correct.

My code: (hopeful correct, I have to join more source files into this one code)

public class DateFormattedTextField extends JFormattedTextField{

private static final String datePattern = "dd.MM.yyyy";
private SimpleDateFormat sdf;

private static class DateMaskFormatter extends MaskFormatter{

public DateMaskFormatter(String mask){
try {
this.setMask(mask);
this.setPlaceholderCharacter('_');
} catch (ParseException ex) {
Logger.getLogger(DateMaskFormatter.class.getName()).log(Level.SEVERE, null, ex);
}
}

}

private class TextDocument extends LimitDocument {

TextDocument() {
super(null);
}

TextDocument(Integer limit) {
super(limit);
}

@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (str == null)
return;
String oldString = getText(0, getLength());
String newString = oldString.substring(0, offs) + str
+ oldString.substring(offs);
if(isValueValid(newString)){
super.insertString(offs, str, a);
}
else{
if(offs == 0){
super.insertString(offs, getMaskString(), a);
}
}
}
}

public DateFormattedTextField(){
super(new DateMaskFormatter("##.##.####"));
this.setDocument(new TextDocument());
sdf = new SimpleDateFormat(datePattern);
sdf.setLenient(false);
}

public boolean isValueValid(String string) {
String tmp = string.replaceAll("_", "1");
try{
sdf.parse(tmp);
}
catch(ParseException e){
return false;
}
return true;
}

public String getMaskString(){
return "__.__.____";
}

}

Can anybody help me?

Thank you

Michael

Message was edited by: anaq