Meaningless Drivel is fun!
The moose likes Swing / AWT / SWT and the fly likes Limit JTextField number of characters Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Reply locked New topic

Limit JTextField number of characters

Wael Atef

Joined: May 14, 2003
Posts: 13
Hi all,
i want to limit the number of characters a JTextField can accept to maximum of 6 characters so that any characters typed by the user beyond these characters not shown in TextField. How can i petrform that.
Abhik Sarkar
Ranch Hand

Joined: Jun 14, 2003
Posts: 61
You can use a javax.swing.InputVerifier to validate your JTextField.
Here is an example:

[ June 16, 2003: Message edited by: Abhik Sarkar ]
Soniya Ahuja
Ranch Hand

Joined: Jul 20, 2008
Posts: 83

I tried the code sample given above. But it's not working . I'm working with JDK 5. I've added this text field to a jframe. Here's the code

I am still able to type beyond 6 characters in the text field

SCJP 1.5 | SCWCD 5 | SCJP 6.0
[url][/url] - Online training for Java/JSPs and Servlets/SCJP/SCWCD
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10824

In future, please start a new thread for your questions. Also, this particular thread is 6 years old.

The InputVerifier is not the correct solution. InputVerifier only ensures that the component will not loose focus in case the validation fails. It does not enforce the input conditions as you want.
This question comes up quite a few times and has been answered before. Search the forums.
The ranch Swing FAQ also has an article on numeric text fields with sample code. You can adapt the code to suit your requirements.

[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
I agree. Here's the link:
subject: Limit JTextField number of characters
jQuery in Action, 3rd edition