import java.awt.Toolkit;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/*
 * Created on Dec 5, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author brian
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class DoubleDocument extends PlainDocument 
{
	private int maxNumDigits;
	public DoubleDocument(int maxDigits)
	{
		super();
		this.maxNumDigits = maxDigits;
		
	}
	public void insertString(int offset, String string, AttributeSet attributes)
	  throws BadLocationException 
	  {
	
		if (string == null) {
		  return;
		} 
		else if (getLength() + string.length() > this.maxNumDigits){
			Toolkit.getDefaultToolkit().beep();
			return;
		  }
		else {
		  String newValue;
		  int length = getLength();
		  if (length == 0) {
		    newValue = string;
		  } 
		  
		  else {
		    String currentContent =
		      getText(0, length); 
		    StringBuffer currentBuffer =
		      new StringBuffer(currentContent);
		    currentBuffer.insert(offset, string);
		    newValue = currentBuffer.toString();
		  }
		  try {
		  	
		    double x = Double.parseDouble(newValue);
		    if(x < 0 || x > 1.0)
		    	throw new NumberFormatException();
		    super.insertString(offset, string,
		      attributes);
		  }
		  catch (NumberFormatException exception) {
		    Toolkit.getDefaultToolkit().beep();
		  }
		}
	}
}