Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / November 2003

Tip: Looking for answers? Try searching our database.

Max num of enterable characters in a TextField/JTextField

Thread view: 
Gregg Dameron - 26 Nov 2003 23:18 GMT
How does one specify the maximum number of characters that may be entered in
a TextField or JTextField?

Gregg
Christophe Vanfleteren - 27 Nov 2003 00:17 GMT
> How does one specify the maximum number of characters that may be entered
> in a TextField or JTextField?
>
> Gregg

You'll need to implement a custom Document that refuses to accept any more
input once the max length has been entered (this only works for Swing
though).
Something like this would do:

public class LimitedLengthDocument extends javax.swing.text.PlainDocument {

 private int maxLength;

 /** Creates a new instance of LimitedLengthDocument */
 public LimitedLengthDocument( int maxLength) {
   this.maxLength =maxLength;
 }

 public LimitedLengthDocument() {
   this.maxLength = 3;
 }

 void setMaxLength(int maxLength) {
   this.maxLength = maxLength;
 }

public void insertString(int offset, String str, AttributeSet a) throws
BadLocationException {
   if ((getLength() + str.length()) <= maxLength) {
     super.insertString(offset, str, a);
   }else{
     java.awt.Toolkit.getDefaultToolkit().beep();
   }
 }
}

You'll need to give an instance of this document to your JTextField.

Signature

Regards,
Christophe Vanfleteren

Gordon Tillman - 27 Nov 2003 18:49 GMT
Hi Gregg,

Another way to do this...

> How does one specify the maximum number of characters that may be entered in
> a TextField or JTextField?

...if you are using Java 1.4+ is with a JFormattedTextField.  You can
do all sorts of cool input validation with it.

--g


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.