Search code examples
javaswinguser-interfacedocumentjtextfield

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?


Solution

  • 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.