Posted By:
Gautam_Marwaha
Posted On:
Sunday, August 18, 2002 09:27 PM
You can - with some extra code. One popular way is:
import javax.swing.*;
import java.awt.Toolkit;
import javax.swing.text.*;
public class LimitedLengthDocument extends PlainDocument
{
protected int maxLength;
public LimitedLengthDocument(int maxLength)
{
this.maxLength = maxLength;
}
public int maxLength()
{
return maxLength;
}
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException
{
if (str == null) return;
int strLen = str.length();
if (strLen == 0) return;
int len = getLength();
if (strLen + len > maxLength)
{
Toolkit.getDefaultToolkit().beep();
str = str.substring(0, maxLength - len); // or return;
}
super.insertString(offs, str, a);
}
}
JTextField f = new JTextField(new LimitedLengthDocument(20), "", 20);