EarthWeb
Developer.com
Site
windows 2000
visual c++
java
visual basic
javascripts
recommend it
 
Book
thinking in java
 
Interact
forum
guest book
jobs
jokes
what's new

share code
 
Resource
add resource
modify resource
new resource
 

[Internet Jobs]
-----
Java by E-mail:

Get the weekly e-mail highlights on Java!
-----

-

Limit JTextField input to a maximum length


Author: Real Gagnon
Author's WebSite: http://tactika.com/realhome/realhome.html


 import com.sun.java.swing.text.*;
 //import javax.swing.text.*;
 public class JTextFieldLimit extends PlainDocument {
   private int limit;
   // optional uppercase conversion
   private boolean toUppoercase = false;
   
   JTextFieldLimit(int limit) {
    super();
    this.limit = limit;
    }
    
   JTextFieldLimit(int limit, boolean upper) {
    super();
    this.limit = limit;
    toUppercase = upper;
    }
  
   public void insertString
     (int offset, String  str, AttributeSet attr)
       throws BadLocationException {
    if (str == null) return;

    if ((getLength() + str.length()) <= limit) {
      if (toUppercase) str = str.toUpperCase();
      super.insertString(offset, str, attr);
      }
    }
 }



Usage


  import java.awt.*; 
  import com.sun.java.swing.*;
  //import javax.swing.*;

  public class tswing extends JApplet{
    JTextField textfield1;
    JLabel label1;

    public void init() {
      getContentPane().setLayout(new FlowLayout());
      //
      label1 = new JLabel("max 10 chars");
      textfield1 = new JTextField(15);
      getContentPane().add(label1);
      getContentPane().add(textfield1);
      textfield1.setDocument
         (new JTextFieldLimit(10));
      }
  }



Posted On: 5-Jul-1999

internet.commerce



Acceptable Use Policy

JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Web Hosting | Newsletters | Tech Jobs | Shopping | E-mail Offers