3 import javax.swing.JTextField;
4 import javax.swing.event.DocumentEvent;
5 import javax.swing.event.DocumentListener;
6 import javax.swing.text.AttributeSet;
7 import javax.swing.text.BadLocationException;
8 import javax.swing.text.PlainDocument;
11 * text field for holding a single integer with validation
13 public class WholeNumberField extends JTextField
16 * Inner class to act as document for validation
18 protected static class WholeNumberDocument extends PlainDocument
20 /** Num digits to allow */
21 private int _maxDigits = 0;
25 * @param inMaxDigits max digits to allow
27 public WholeNumberDocument(int inMaxDigits)
29 _maxDigits = inMaxDigits;
34 * Override the insert string method
38 * @throws BadLocationException on insert failure
40 public void insertString(int offs, String str, AttributeSet a)
41 throws BadLocationException
43 if (getLength() >= _maxDigits) return;
44 char[] source = str.toCharArray();
45 char[] result = new char[source.length];
47 for (int i = 0; i < result.length && j < _maxDigits; i++) {
48 if (Character.isDigit(source[i]))
49 result[j++] = source[i];
51 super.insertString(offs, new String(result, 0, j), a);
58 * @param inMaxDigits max digits to allow
60 public WholeNumberField(int inMaxDigits)
63 setDocument(new WholeNumberDocument(inMaxDigits));
64 getDocument().addDocumentListener(new DocumentListener() {
65 public void removeUpdate(DocumentEvent arg0) {fireActionPerformed();}
66 public void insertUpdate(DocumentEvent arg0) {fireActionPerformed();}
67 public void changedUpdate(DocumentEvent arg0) {fireActionPerformed();}
72 * @return integer value
76 return parseValue(getText());
80 * @param inValue value to set
82 public void setValue(int inValue)
84 setText("" + inValue);
88 * @param inText text to parse
89 * @return value as integer
91 private static int parseValue(String inText)
95 value = Integer.parseInt(inText);
97 catch (NumberFormatException nfe) {}