1    package com.instantbank.common.uiutils;
2    
3    import java.awt.Toolkit;
4    import javax.swing.text.PlainDocument;
5    import javax.swing.text.AttributeSet;
6    import javax.swing.text.BadLocationException;
7    
8    /**
9     * Auxiliary class suited for restricting input for a JTextField to
10    * numeric strings.
11    *
12    * @author InstantBank (Rodrigo Lopez)
13    * @created nov-2002
14    */
15   class IntegerDocument extends PlainDocument {
16   
17     /**
18      * Input must be positive or zero
19      */
20     public static final int POSITIVE = 1;
21   
22     /**
23      * Input must be negative or zero
24      */
25     public static final int NEGATIVE = 2;
26   
27     /**
28      * Input can be positive or negative
29      */
30     public static final int ALL = 3;
31   
32     /**
33      * Allowed range for the input (POSITIVE, NEGATIVE, ALL)
34      */
35     private int range;
36   
37   
38     /**
39      * IntegerDocument constructor.
40      *
41      * @param range Allowed range for the input (POSITIVE, NEGATIVE, ALL)
42      */
43     public IntegerDocument(int range) {
44       this.range = range;
45     }
46   
47   
48     /**
49      * Redefinition of the method from the PlainDocument class.
50      *
51      * @param offset Description of the Parameter
52      * @param s Description of the Parameter
53      * @param attributeSet Description of the Parameter
54      * @throws BadLocationException Description of the Exception
55      */
56     public void insertString(int offset, String s, AttributeSet attributeSet)
57        throws BadLocationException {
58       try {
59         int val = Integer.parseInt(s);
60         if(range == POSITIVE && val < 0 || range == NEGATIVE && val > 0) {
61           throw new Exception();
62         }
63       }
64       catch(Exception ex) {
65         Toolkit.getDefaultToolkit().beep();
66         return;
67       }
68       super.insertString(offset, s, attributeSet);
69     }
70   }
71