Une réponse tardive à une vieille question ; faire usage de DocumentFilter
peut atteindre ces trois exigences.
un code de qualité hors production peut ressembler à ceci
String TIME_PATTERN = "^\\d\\d:\\d\\d\\s[AP]M$";
final JTextField tf = new JTextField("00:00 AM", 8);
((AbstractDocument)tf.getDocument()).setDocumentFilter(new DocumentFilter() {
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
String text = fb.getDocument().getText(0, fb.getDocument().getLength());
text = text.substring(0, offs) + str + text.substring(offs + length);
if(text.matches(TIME_PATTERN)) {
super.replace(fb, offs, length, str, a);
return;
}
text = fb.getDocument().getText(0, fb.getDocument().getLength());
if(offs == 2 || offs == 5)
tf.setCaretPosition(++offs);
if(length == 0 && (offs == 0 ||offs == 1 ||offs == 3 ||offs == 4 ||offs == 6))
length = 1;
text = text.substring(0, offs) + str + text.substring(offs + length);
if(!text.matches(TIME_PATTERN))
return;
super.replace(fb, offs, length, str, a);
}
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException { }
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { }
});