// $Id: SmoothJTextField.java,v 1.1 2007/01/30 16:21:23 jtrent Exp $
import javax.swing.JTextField;
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
/**
* SmoothJTextField performs identically to a JTextField except that it
* uses anti-aliasing and allows the programmer to specifiy a maximum
* input string length.
*
* @see JTextField
*
* @author Jason R Trent - jtrent@sandia.gov - Sandia National Laboratories
* @version $Revision: 1.1 $
*/
class SmoothJTextField extends JTextField
{
private int maxLength = 20;
public SmoothJTextField()
{
this( "", 20 );
}
public SmoothJTextField( int limit )
{
this( "", limit );
}
public SmoothJTextField( String label )
{
this( label, 20 );
}
public SmoothJTextField( String label, int limit )
{
super();
maxLength = limit;
if( label.length() > limit )
label = label.substring( 0, limit );
setText( label );
setDocument( new PlainDocument()
{
public void insertString( int offset, String str, AttributeSet attribSet )
{
if( str == null )
return;
try
{
String oldStr = getText( 0, getLength() );
String newStr = oldStr.substring( 0, offset ) + str + oldStr.substring( offset );
if( isValid( newStr ) )
super.insertString( offset, str, attribSet );
}
catch( BadLocationException exception ) {}
return;
}
public boolean isValid( String str )
{
if( str.length() <= maxLength )
return true;
else
return false;
}
} );
}
public void paint(Graphics g)
{
((Graphics2D) g).setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
super.paint( g );
}
public int getMaxLength()
{
return maxLength;
}
public void setMaxLength( int limit )
{
maxLength = limit;
return;
}
};
/* End of File */