<p>JTextField size?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   florent_thomas
Posted On:   Sunday, August 18, 2002 02:04 PM


Is it possible to fix the size, I mean the max number of character , of a JTextField. Thanx for ur help!

Re: <p>JTextField size?

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);
About | Sitemap | Contact