Простенький не получится.
| Код | public class MyFormatter extends JFormattedTextField.AbstractFormatter { public void install(JFormattedTextField ftf) { Document doc = ftf.getDocument(); if(doc instanceof AbstractDocument) ((AbstractDocument) doc).setDocumentFilter(new NumberFilter()); }
public Object stringToValue(String text) throws ParseException { //распарсить строку, для даты можно использовать SimpleDateFormat }
public String valueToString(Object value) throws ParseException { //преобразовать объект в строку, для даты опять же можно использовать SimpleDateFormat } } |
| Код | public class NumberFilter extends DocumentFilter { private Document document;
public NumberFilter(Document document) { this.document = document; }
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { if(string.length() + document.getLength() < 2)//проверяем общую длинну документа { if(checkChar(offset, string)) fb.insertString(offset, string, attr); } }
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if(text.length() + document.getLength() - length < 2)//проверяем общую длинну документа { if(checkChar(offset, text)) fb.replace(offset, length, text, attrs); } }
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { fb.remove(offset, length);//удалять можно всегда }
private boolean checkChar(int offset, String string) { boolean result = true; for(int i = string.length(); i >= 0; i--) { char c = string.charAt(i); //проверяем допустимость данного символа, на данной (offset+i) позиции. Если нет, то result = false } return result; } } |
|