01: /*
02: * Created on 26.02.2004
03: */
04: package org.gui4j.core.swing;
05:
06: import javax.swing.text.AttributeSet;
07: import javax.swing.text.BadLocationException;
08: import javax.swing.text.DocumentFilter;
09:
10: /**
11: * @author MarcusT
12: */
13: public class MaxLengthDocumentFilter extends DocumentFilter {
14: private final int max;
15:
16: public MaxLengthDocumentFilter(int max) {
17: super ();
18: this .max = max;
19: }
20:
21: public void insertString(FilterBypass fb, int offset,
22: String string, AttributeSet attr)
23: throws BadLocationException {
24: int overflow = fb.getDocument().getLength() + string.length()
25: - max;
26: if (overflow <= 0) {
27: super .insertString(fb, offset, string, attr);
28: } else {
29: super .insertString(fb, offset, string.substring(0, string
30: .length()
31: - overflow), attr);
32: }
33: }
34:
35: public void replace(FilterBypass fb, int offset, int length,
36: String text, AttributeSet attrs)
37: throws BadLocationException {
38:
39: int textlength = text == null ? 0 : text.length();
40: int overflow = fb.getDocument().getLength() - length
41: + textlength - max;
42: if (overflow <= 0) {
43: super .replace(fb, offset, length, text, attrs);
44: } else {
45: super .replace(fb, offset, length, text.substring(0,
46: textlength - overflow), attrs);
47: }
48:
49: }
50:
51: }
|