For the above answer below is a Utility method I have created to deal with above situations -
/**
* Method installNumericMaximumCharacters.
*
* @param document
* AbstractDocument
* @param numberofChars
* int
*/
public static void installNumericMaximumCharacters(
AbstractDocument document, final int numberofChars) {
document.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
try {
if (string.equals(".")
&& !fb.getDocument()
.getText(0, fb.getDocument().getLength())
.contains(".")) {
super.insertString(fb, offset, string, attr);
return;
}
Double.parseDouble(string);
if (fb.getDocument().getLength() + string.length() <= numberofChars) {
super.insertString(fb, offset, string, attr);
} else {
Toolkit.getDefaultToolkit().beep();
}
} catch (Exception e) {
Toolkit.getDefaultToolkit().beep();
}
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs)
throws BadLocationException {
try {
if (text.equals(".")
&& !fb.getDocument()
.getText(0, fb.getDocument().getLength())
.contains(".")) {
super.insertString(fb, offset, text, attrs);
return;
}
Double.parseDouble(text);
int l = fb.getDocument().getLength() - length
+ text.length();
if (length > 0) {
fb.getDocument().remove(offset, length);
}
if (l <= numberofChars) {
super.insertString(fb, offset, text, attrs);
} else {
Toolkit.getDefaultToolkit().beep();
}
} catch (Exception e) {
Toolkit.getDefaultToolkit().beep();
}
}
});
}
The method is bit self explanatory. When ever a change occurs on the Document
it will evoke the DocumentFilter
. Beware that you cannot setText()
the same Document
. You will have to use the FilterBypass
object for it.