01: /*
02: * Jacareto Copyright (c) 2002-2005
03: * Applied Computer Science Research Group, Darmstadt University of
04: * Technology, Institute of Mathematics & Computer Science,
05: * Ludwigsburg University of Education, and Computer Based
06: * Learning Research Group, Aachen University. All rights reserved.
07: *
08: * Jacareto is free software; you can redistribute it and/or
09: * modify it under the terms of the GNU General Public
10: * License as published by the Free Software Foundation; either
11: * version 2 of the License, or (at your option) any later version.
12: *
13: * Jacareto is distributed in the hope that it will be useful,
14: * but WITHOUT ANY WARRANTY; without even the implied warranty of
15: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16: * General Public License for more details.
17: *
18: * You should have received a copy of the GNU General Public
19: * License along with Jacareto; if not, write to the Free
20: * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21: *
22: */
23:
24: package jacareto.cleverphl.gui;
25:
26: import java.awt.Toolkit;
27:
28: import java.text.NumberFormat;
29: import java.text.ParseException;
30:
31: import java.util.Locale;
32:
33: import javax.swing.JTextField;
34: import javax.swing.text.AttributeSet;
35: import javax.swing.text.BadLocationException;
36: import javax.swing.text.Document;
37: import javax.swing.text.PlainDocument;
38:
39: public class WholeNumberField extends JTextField {
40: private Toolkit toolkit;
41: private NumberFormat integerFormatter;
42:
43: public WholeNumberField(int value, int columns) {
44: super (columns);
45: toolkit = Toolkit.getDefaultToolkit();
46: integerFormatter = NumberFormat.getNumberInstance(Locale.US);
47: integerFormatter.setParseIntegerOnly(true);
48: setValue(value);
49: }
50:
51: public int getValue() {
52: int retVal = 0;
53:
54: try {
55: retVal = integerFormatter.parse(getText()).intValue();
56: } catch (ParseException e) {
57: // This should never happen because insertString allows
58: // only properly formatted data to get in the field.
59: toolkit.beep();
60: }
61:
62: return retVal;
63: }
64:
65: public void setValue(int value) {
66: setText(integerFormatter.format(value));
67: }
68:
69: protected Document createDefaultModel() {
70: return new WholeNumberDocument();
71: }
72:
73: protected class WholeNumberDocument extends PlainDocument {
74: //~ Methods --------------------------------------------------------------------------------
75:
76: public void insertString(int offs, String str, AttributeSet a)
77: throws BadLocationException {
78: char[] source = str.toCharArray();
79: char[] result = new char[source.length];
80: int j = 0;
81:
82: for (int i = 0; i < result.length; i++) {
83: if (Character.isDigit(source[i])) {
84: result[j++] = source[i];
85: } else {
86: toolkit.beep();
87: }
88: }
89:
90: super .insertString(offs, new String(result, 0, j), a);
91: }
92: }
93: }
|