tags:

views:

61

answers:

1

How to limit the number of characters entered in a JTextField?

Suppose I want to enter say 5 characters max. After that no characters can be entered into it.

+4  A: 

http://www.rgagnon.com/javadetails/java-0198.html

import javax.swing.text.PlainDocument

public class JTextFieldLimit extends PlainDocument {
  private int limit;

  JTextFieldLimit(int limit) {
   super();
   this.limit = limit;
   }

  public void insertString( int offset, String  str, AttributeSet attr ) throws BadLocationException {
    if (str == null) return;

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

Then

import java.awt.*;
import javax.swing.*;

 public class DemoJTextFieldWithLimit 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));
     }
}

(first result from google)

tim_yates
Some more comments to explain the answer would be welcome.
jfpoilpret
is there no direct function like textfield.maximumlimit(10);
Santosh V M
No, and it tells you to use a class that extends `PlainDocument` in the javadoc for `JTextField` http://download.oracle.com/javase/6/docs/api/javax/swing/JTextField.html
tim_yates
I'm getting two errors when I enter the above mentioned code.1 - package com.sun.java.swing.text does not exist2 - cannot find symbol PlainDocument
Santosh V M
Sorry...should be working now...
tim_yates
thanks tim_yates for the help will check it out now.will this JTextFieldLimit class work even for password field also?
Santosh V M
By the way could you please explain how the character limiting takes place through the "JTextFieldLimit" class. It will be helpful.
Santosh V M