Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting Length of Input in JTextField is not working

I am trying to limit the max length of character a user can input in a textfield but It seems to be not working.

Here is the code:

text2 = new JTextField("Enter text here",8);

Is there anything I am doing wrong? How can I make the limit to work properly?

like image 624
Naruto Avatar asked Oct 25 '12 19:10

Naruto


1 Answers

You current code is not setting the maximum length, rather it is defining the number of visible columns.

To restrict the maximum length of the data, you can set a custom Document for the text field that does not permit additions that break the maximum length restriction:

public final class LengthRestrictedDocument extends PlainDocument {

  private final int limit;

  public LengthRestrictedDocument(int limit) {
    this.limit = limit;
  }

  @Override
  public void insertString(int offs, String str, AttributeSet a)
      throws BadLocationException {
    if (str == null)
      return;

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

Then set your text field to use this document:

text2.setDocument(new LengthRestrictedDocument(8));
like image 188
Duncan Jones Avatar answered Oct 01 '22 03:10

Duncan Jones