| 7 | public class NumericDocument extends PlainDocument |
| 8 | { |
| 9 | public void insertString(int offset, String string, AttributeSet attributes) |
| 10 | throws BadLocationException |
| 11 | { |
| 12 | if (string != null) { |
| 13 | int stringLength = string.length(); |
| 14 | char initialChar; |
| 15 | if (getLength() > 0) |
| 16 | initialChar = getText(0, 1).charAt(0); |
| 17 | else { |
| 18 | initialChar = ' '; |
| 19 | } |
| 20 | if (stringLength == 0) { |
| 21 | super.insertString(offset, string, attributes); |
| 22 | } else if (stringLength == 1) { |
| 23 | char c = string.charAt(0); |
| 24 | if (Character.isDigit(c)) { |
| 25 | if ((offset != 0) || (initialChar != '-')) |
| 26 | super.insertString(offset, string, attributes); |
| 27 | } else if ((c == '-') && |
| 28 | (offset == 0) && (initialChar != '-')) |
| 29 | super.insertString(offset, string, attributes); |
| 30 | } |
| 31 | else { |
| 32 | StringBuilder buffer = new StringBuilder(string); |
| 33 | int index = 0; |
| 34 | while (index < stringLength) { |
| 35 | if ((offset == 0) && (index == 0)) { |
| 36 | char c = buffer.charAt(0); |
| 37 | if (Character.isDigit(c)) { |
| 38 | if (initialChar == '-') { |
| 39 | buffer.deleteCharAt(index); |
| 40 | stringLength--; |
| 41 | } else { |
| 42 | index++; |
| 43 | } |
| 44 | } else if (c == '-') { |
| 45 | if (initialChar != '-') { |
| 46 | index++; |
| 47 | } else { |
| 48 | buffer.deleteCharAt(index); |
| 49 | stringLength--; |
| 50 | } |
| 51 | } else { |
| 52 | buffer.deleteCharAt(index); |
| 53 | stringLength--; |
| 54 | } |
| 55 | } |
| 56 | else if (Character.isDigit(buffer.charAt(index))) { |
| 57 | index++; |
| 58 | } else { |
| 59 | buffer.deleteCharAt(index); |
| 60 | stringLength--; |
| 61 | } |
| 62 | |
| 63 | } |
| 64 | |
| 65 | super.insertString(offset, buffer.toString(), attributes); |
| 66 | } |