3 import javax.swing.JTextField;
4 import javax.swing.text.AttributeSet;
5 import javax.swing.text.BadLocationException;
6 import javax.swing.text.PlainDocument;
9 * text field for holding a single integer with validation
11 public class WholeNumberField extends JTextField
14 * Inner class to act as document for validation
16 protected static class WholeNumberDocument extends PlainDocument
18 /** Num digits to allow */
19 private int _maxDigits = 0;
23 * @param inMaxDigits max digits to allow
25 public WholeNumberDocument(int inMaxDigits)
27 _maxDigits = inMaxDigits;
32 * Override the insert string method
36 * @throws BadLocationException on insert failure
38 public void insertString(int offs, String str, AttributeSet a)
39 throws BadLocationException
41 if (getLength() >= _maxDigits) return;
42 char[] source = str.toCharArray();
43 char[] result = new char[source.length];
45 for (int i = 0; i < result.length && j < _maxDigits; i++) {
46 if (Character.isDigit(source[i]))
47 result[j++] = source[i];
49 super.insertString(offs, new String(result, 0, j), a);
56 * @param inMaxDigits max digits to allow
58 public WholeNumberField(int inMaxDigits)
61 setDocument(new WholeNumberDocument(inMaxDigits));
65 * @return integer value
69 return parseValue(getText());
73 * @param inValue value to set
75 public void setValue(int inValue)
77 setText("" + inValue);
81 * @param inText text to parse
82 * @return value as integer
84 private static int parseValue(String inText)
88 value = Integer.parseInt(inText);
90 catch (NumberFormatException nfe) {}