3 import java.awt.Dimension;
5 import javax.swing.JTextField;
6 import javax.swing.text.AttributeSet;
7 import javax.swing.text.BadLocationException;
8 import javax.swing.text.PlainDocument;
11 * text field for holding a decimal number with validation
12 * - doesn't allow certain characters such as a-z to be entered
14 public class DecimalNumberField extends JTextField
17 * Inner class to act as document for validation
19 protected static class DecimalNumberDocument extends PlainDocument
21 private boolean _allowNegative = false;
24 DecimalNumberDocument(boolean inAllowNegative) {
25 _allowNegative = inAllowNegative;
29 * Override the insert string method
33 * @throws BadLocationException on insert failure
35 public void insertString(int offs, String str, AttributeSet a)
36 throws BadLocationException
38 char[] source = str.toCharArray();
39 char[] result = new char[source.length];
41 for (int i = 0; i < result.length; i++) {
42 if (!Character.isLetter(source[i]) && (_allowNegative || source[i] != '-') && source[i] != ' ') // no letters, no minus sign or space
43 result[j++] = source[i];
45 super.insertString(offs, new String(result, 0, j), a);
53 public DecimalNumberField()
60 * @param inAllowNegative true to allow negative numbers
62 public DecimalNumberField(boolean inAllowNegative)
65 setDocument(new DecimalNumberDocument(inAllowNegative));
69 * @return double value
71 public double getValue()
73 return parseValue(getText());
77 * @param inValue value to set
79 public void setValue(double inValue)
81 setText("" + inValue);
85 * @param inText text to parse
86 * @return value as double
88 private static double parseValue(String inText)
92 value = Double.parseDouble(inText);
94 catch (NumberFormatException nfe) {}
102 * Put a minimum on the minimum width
104 public Dimension getMinimumSize()
106 Dimension dim = super.getMinimumSize();
107 if (dim.width < 50) dim.width = 50;