Hey,
I am trying to find a way to limit how many characters a user can enter into a JTextField.
Does anyone know how to do this?
Thanks!

Personally, my first instinct would be to write a listener method that got the text, counted how many characters were there, and "refused to let more be entered" by setting the text back to whatever was previously there if the user entered too much. That would work, however, my first instinct would probably be a waste of time, because there are other available methods of doing the same with less effort and probably less code.


At this link, it describes that you should either use a JFormattedTextField (you're using a JTextField) or you should use a Document listener. It gives links to both. If you want to use a JTextField, stick with the document listener.
http://java.sun.com/docs/books/tutorial/uiswing/components/textfield.html

commented: Good suggestion. +22

Hi Poster,

BestJewSinceJC's explanation is correct. There is no direct method to force user to restrict input.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.