01: package examples.swingdemos;
02:
03: import java.awt.*;
04: import java.text.*;
05: import java.util.*;
06:
07: import javax.swing.*;
08: import javax.swing.text.*;
09:
10: public class WholeNumberField extends JTextField {
11: Toolkit toolkit;
12: private NumberFormat integerFormatter;
13:
14: public WholeNumberField(int value, int columns) {
15: super (columns);
16: toolkit = Toolkit.getDefaultToolkit();
17: integerFormatter = NumberFormat.getNumberInstance(Locale.US);
18: integerFormatter.setParseIntegerOnly(true);
19: setValue(value);
20: }
21:
22: public int getValue() {
23: int retVal = 0;
24: try {
25: retVal = integerFormatter.parse(getText()).intValue();
26: } catch (ParseException e) {
27: // This should never happen because insertString allows
28: // only properly formatted data to get in the field.
29: toolkit.beep();
30: }
31: return retVal;
32: }
33:
34: public void setValue(int value) {
35: setText(integerFormatter.format(value));
36: }
37:
38: protected Document createDefaultModel() {
39: return new WholeNumberDocument();
40: }
41:
42: protected class WholeNumberDocument extends PlainDocument {
43: public void insertString(int offs, String str, AttributeSet a)
44: throws BadLocationException {
45: char[] source = str.toCharArray();
46: char[] result = new char[source.length];
47: int j = 0;
48:
49: for (int i = 0; i < result.length; i++) {
50: if (Character.isDigit(source[i]))
51: result[j++] = source[i];
52: else {
53: toolkit.beep();
54: System.err.println("insertString: " + source[i]);
55: }
56: }
57: super .insertString(offs, new String(result, 0, j), a);
58: }
59: }
60: }
|