Use This
import javax.swing.JTextField;
import javax.swing.text.PlainDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.AttributeSet;
public class CharLimiter extends PlainDocument
{
int x=0;
CharLimiter(int x)
{
this.x=x;
}
public void insertString(int offs,
String str, AttributeSet a) throws BadLocationException {
if(str.length() > x-1 || this.getLength()> x-1) {
java.awt.Toolkit.getDefaultToolkit().beep();
return;
}
super.insertString(offs, str, a);
}
}
Now ur text field will be initialized as
JTextField txtName=new JTextField(new CharLimiter(4),"",5);
Enjoy