/*
 *This library is free software; you can redistribute it and/or
 *modify it under the terms of the GNU Lesser General Public
 *License as published by the Free Software Foundation; either
 *version 2.1 of the License, or (at your option) any later version.
 *
 *This library is distributed in the hope that it will be useful,
 *but WITHOUT ANY WARRANTY; without even the implied warranty of
 *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *Lesser General Public License for more details.
 *
 *You should have received a copy of the GNU Lesser General Public
 *License along with this library; if not, write to the Free Software
 *Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package uk.ac.man.bioinf.gui.util.forms;
import javax.swing.*; 
import javax.swing.text.*; 

import java.awt.Toolkit;
import java.text.*;

/**
 * Provides a validated field that only accepts decimal numbers.
 * @author C.Miller
 * @version 1.0
 */
public class DecimalField extends JTextField {
   private NumberFormat format;
   
   public DecimalField(int columns, NumberFormat f) {
      super(columns);
      setDocument(new FormattedDocument(f));
      format = f;
   }
   
   public DecimalField(double value, int columns, NumberFormat f) {
      super(columns);
      setDocument(new FormattedDocument(f));
      format = f;
      setValue(value);
   }

   public boolean isValid() {
      try {
         format.parse(getText()).intValue();
      } catch (ParseException e) {
         // This should never happen because insertString allows
         // only properly formatted data to get in the field.
         return false;
      }
      return true;
   }

   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));
   }
}
