Article View: borland.public.jbuilder.java.language
Article #14637Re: JTextField size
From: David
Date: Mon, 09 Aug 1999 00:00
Date: Mon, 09 Aug 1999 00:00
49 lines
2017 bytes
2017 bytes
Here is the solution that I am using to restrict the number of characters
the JTextField allows. I found it on the java web site and changed the beep
since it would beep for each JTextfield at the constructor. Anyway, it
seems to do the trick. Hope it helps.
import java.awt.Toolkit;
import javax.swing.*;
import javax.swing.text.*;
// An extension of PlainDocument that restricts the length of the content it
contains
public class FixedLengthPlainDocument extends PlainDocument {
private int maxLength;
public FixedLengthPlainDocument(int maxLength) {
this.maxLength = maxLength;
}
public void insertString(int offset, String str, AttributeSet a) throws
BadLocationException {
if (getLength() + str.length() > maxLength) {
str = str.substring(0, str.length() - (getLength() +
str.length() - maxLength));
super.insertString(offset, str, a);
//Toolkit.getDefaultToolkit().beep();
}
else {
super.insertString(offset, str,a);
}
}
}
David wrote:
> Good day -
>
> Using JBuilder 3 -
>
> I have several JTextFields that the user types into. I would like to
> restrict the number of characters to 10 (for example). Has anyone done
> this? I thought perhaps DocumentListener was the solution, but couldn't
> get it to work.
>
> I would greatly appreciate any help you can offer.
>
> David
Technical Details
Message-ID:
<37AEFC33.A3E71EB2@lmco.com>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<37A9FA85.279DCA47@lmco.com>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f74b3,4e0efe8fe5a13afc X-Google-Attributes: gidf74b3,public From: David <david.v.clark@lmco.com> Subject: Re: JTextField size Date: 1999/08/09 Message-ID: <37AEFC33.A3E71EB2@lmco.com> X-Deja-AN: 510640601 Content-Transfer-Encoding: 7bit References: <37A9FA85.279DCA47@lmco.com> X-Accept-Language: en Content-Type: text/plain; charset=us-ascii Organization: Another Netscape Collabra Server User Mime-Version: 1.0 Newsgroups: borland.public.jbuilder.java.language