6

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?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Naruto
  • 1,710
  • 7
  • 28
  • 39

4 Answers4

19

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));
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
9

The constructor

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

sets the number of visible columns to 8 but doesn't restrict you from entering more.

You could use a DocumentFilter to restrict the input length.

Community
  • 1
  • 1
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 1
    You can find a good example on how to do this here (http://www.java2s.com/Tutorial/Java/0240__Swing/LimitJTextFieldinputtoamaximumlength.htm). – Designpattern Dec 18 '13 at 15:06
0

Simply extend the JTextField Class and override the KeyReleased event in the constructor and point it on a new method that checks the length:

package gui;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JTextField;

public class RecordClassTextField extends JTextField {

    public RecordClassTextField() {
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                cleanText();
            }
        });
    }

    private void cleanText()
    {
        if(this.getText().length() > 17){
            System.out.println("Over 17");
        }
    }
}
angrydad
  • 11
  • 1
-1

No need to use any API
Simply write this code on TextFieldKeyTyped event

if (jTextField.getText().trim().length() == 8 || evt.getKeyChar() == java.awt.event.KeyEvent.VK_BACK_SPACE) {
        evt.consume();
    }  

And before using this code set JTextField property setTransferHandler(null); that will prevent from pasting.