import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

/*
 * 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
 */
class IntegerDocument
extends PlainDocument 
{
	private int maxNumDigits;
	public IntegerDocument(int maxDigits)
	{
		super();
		this.maxNumDigits = maxDigits;
		
	}
	public void remove(int off, int len) throws BadLocationException 
	{
		
		String removeText = this.getText(off,len);
		super.remove(off,len);
		try {	
			Integer.parseInt(this.getText(0,getLength()));
		}
		catch (NumberFormatException exception) {
		    Toolkit.getDefaultToolkit().beep();
		    this.insertString(off,removeText,this.getAttributeContext().getEmptySet());
		}
	}
	
	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 {
		    Integer.parseInt(newValue);
		    super.insertString(offset, string,
		      attributes);
		  }
		  catch (NumberFormatException exception) {
		    Toolkit.getDefaultToolkit().beep();
		  }
		}
	}
}
