View Javadoc

1   /*
2    * Adapted from: http://java.sun.com/docs/books/tutorial/uiswing/
3    * components/example-swing/WholeNumberField.java Created on Oct 17, 2003
4    */
5   package ca.spaz.gui;
6   
7   import java.awt.Toolkit;
8   import java.text.DecimalFormat;
9   
10  import javax.swing.JTextField;
11  import javax.swing.text.*;
12  
13  public class DoubleField extends JTextField {
14     private Toolkit toolkit;
15     private double min = Integer.MIN_VALUE, max = Integer.MAX_VALUE;
16     private DecimalFormat df = new DecimalFormat("#########0.0###");
17  
18     public DoubleField(double value, int columns) {
19        super(columns);
20        toolkit = Toolkit.getDefaultToolkit();
21        setValue(value);
22     }
23     
24     public void setRange(double min, double max) {
25        this.min = min;
26        this.max = max;
27     }
28  
29     public double getValue() {
30        double retVal = 0;
31        try {
32           retVal = Double.parseDouble(getText());
33        } catch (NumberFormatException e) {
34           toolkit.beep();
35        }
36        if (retVal < min) retVal = min;
37        if (retVal > max) retVal = max;
38        return retVal;
39     }
40  
41     public void setValue(double value) {
42        if (value < min) value = min;
43        if (value > max) value = max;
44        setText(df.format(value));
45        //setText(Double.toString(value));
46     }
47  
48     protected Document createDefaultModel() {
49        return new DoubleDocument();
50     }
51     
52     protected String getCurrentText() {
53        return getText();
54     }
55  
56     protected class DoubleDocument extends PlainDocument {
57        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
58           char[] source = str.toCharArray();
59           char[] result = new char[source.length];
60           int j = 0;
61           boolean decimal = false;
62           for (int i = 0; i < result.length; i++) {
63              char c = source[i];
64              if (Character.isDigit(c) || (c=='.' && getCurrentText().indexOf('.')==-1)) {
65                 result[j++] = c;
66                 if (c =='.') {
67                    decimal = true;
68                 }
69              } else {
70                 toolkit.beep();
71              }
72           }
73           super.insertString(offs, new String(result, 0, j), a);
74        }
75     }
76  }