package lu.tudor.santec.gecamed.core.gui.widgets;

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


public class LimittedDocument extends PlainDocument
{
	/* ======================================== */
	// 		CONSTANTS
	/* ======================================== */
	
	private static final long	serialVersionUID	= 1L;
	
	
	
	/* ======================================== */
	// 		MEMBERS
	/* ======================================== */
	
	private int limit;
	
	
	
	/* ======================================== */
	// 		CONSTRUCTORS
	/* ======================================== */
	
	public LimittedDocument(int limit)
	{
		this.limit = limit;
	}
	
	
	
	/* ======================================== */
	// 		CLASS BODY
	/* ======================================== */
	
	public int getLimit ()
	{
		return limit;
	}
	
	
	public void setLimit (int limit)
	{
		this.limit = limit;
	}
	
	
	@Override
	public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
	{
		if (str.length() + super.getLength() > limit)
			str = str.substring(0, limit - super.getLength());
		
		super.insertString(offs, str, a);
	}
	
	
	@Override
	public void replace(int offset, int length, String text, AttributeSet attrs) throws BadLocationException
	{
		if (text.length() + super.getLength() - length > limit)
			text = text.substring(0, limit - super.getLength() + length);
		
		super.replace(offset, length, text, attrs);
	}
}
