import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

import AcsCommon.Helper;

public class JTextFieldLimit extends PlainDocument {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int limit;
	// optional uppercase conversion
	private boolean toNumOnly = false;

	JTextFieldLimit(int limit) {
		super();
		this.limit = limit;
	}

	JTextFieldLimit(int limit, boolean numOnly) {
		super();
		this.limit = limit;
		toNumOnly = numOnly;
	}

	public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
		if (str == null)
			return;

		if (toNumOnly) {
			if ((getLength() + str.length()) <= limit && Helper.isHexStringValid(str)) {
				super.insertString(offset, str, attr);
			}
		} else {
			boolean numeric = true;
			try {
				Double.parseDouble(str);
			} catch (NumberFormatException e) {
				numeric = false;
			}
			if ((getLength() + str.length()) <= limit && numeric) {
				super.insertString(offset, str, attr);
			}
		}
	}
}
