import javax.swing.*; 
import javax.swing.text.*; 

import java.awt.Toolkit;

import java.text.*;

public class DecimalField extends JTextField {

    // By attaching a NumberFormat to a text field,
    // this class ensures that only text of that
    // format is entered into the text field.

    // This class could be made to handle integer values
    // by including a constructor that takes an
    // int and by including setIntValue and getIntValue
    // methods. Similarly, one could make this even
    // more general and let it handle dates by
    // letting a program attach a DateFormat to the text field
    // and providing getDateValue and setDateValue methods.

    private NumberFormat format;

    public DecimalField(double value, int columns, NumberFormat f) {
	super(columns);
	setDocument(new FormattedDocument(f));
	format = f;
	setValue(value);
    }

    public double getValue() {
        double retVal = 0.0;

        try {
            retVal = format.parse(getText()).doubleValue();
        } catch (ParseException e) {
            // This should never happen because insertString allows
            // only properly formatted data to get in the field.
            Toolkit.getDefaultToolkit().beep();
            System.err.println("getValue: could not parse: " + getText());
        }
        return retVal;
    }

    public void setValue(double value) {
	setText(format.format(value));
    }
}
