How do I create a TextField that limits the number of characters a user can place in it?

John Zukowski

To limit the number of characters a user can type into the AWT TextField, you need to watch as the user types and count characters. If the size gets too large, you reject input. You need to still permit characters like TAB for moving focus as well as Backspace/Delete for removing characters. The following program demonstrates this.


import java.awt.*;
import java.awt.event.*;
public class SizedTextField extends TextField {
  private int size;  // size = 0 is unlimited
  public SizedTextField () {
    super("");
    this.size = 0;
    init();
  }
  public SizedTextField (int columns) {
    super(columns);
    this.size = 0;
    init();
  }
  public SizedTextField (int columns, int size) {
    super (columns);
    this.size = Math.max (0, size);
    init();
  }
  public SizedTextField (String text) {
    super(text);
    this.size = 0;
    init();
  }
  public SizedTextField (String text, int columns) {
    super(text, columns);
    this.size = 0;
    init();
  }
  public SizedTextField (String text, int columns, int size) {
    super(text, columns);
    this.size = Math.max (0, size);
    init();
  }
  private void init() {
    KeyListener listener = new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if ((size > 0) &&
          (((TextField)(e.getComponent())).getText().length () >= size)) {
          // Check for backspace / delete / tab -- let these pass through
          if ((key == KeyEvent.VK_DELETE) || (key == KeyEvent.VK_TAB) || 
              (key == KeyEvent.VK_BACK_SPACE)) {
            return;
          } else {
            e.consume();
          }
        }
      }
    };
    addKeyListener(listener);
  }
  protected String paramString () {
    String str = super.paramString ();
    if (size != 0) {
      str += ",size=" + size;
    }
    return str;
  }
  public static void main(String args[]) {
    Frame f = new Frame("Test");
    TextField tf1 = new TextField();
    TextField tf2 = new SizedTextField(10, 10);
    f.add(tf1, BorderLayout.NORTH);
    f.add(tf2, BorderLayout.SOUTH);
    f.pack();
    f.show();
  }
}

A note of caution. This does not limit you as a programmer from saying setText() with some really long string.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact