This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I was trying to limit the no. of characters in a JTextField by using Inputverifier class. I am able to acheive that. But now the problem is I can't use backspace, arrow keys, etc. Since I am tracking key press event. I need to track backspace, arrow keys press too. How to track the backspace, arrow keys press?
You can wrap the text fields document in your own class that intercepts the insertString method:
Basically, all text components are backed by an implementation of javax.swing.text.Document. All edits in the text component (adding, removing, etc) are done to the document, and then shown in the text component.
You get that document, wrap it in the wrapper class, and put it back in the text component. This wrapper will make sure that adding something (can be a typed character, or a pasted string) will not cause the maximum length to be exceeded. If this would happen, the string will be cut off so it will cause the maximum length to be reached - but not exceeded.
There is one downside to this. If you use DocumentListeners and add those to "document" directly, that document will be exposed. My own implementation solves that by wrapping DocumentEvents as well, but you won't need that right now.
I was trying to limit the no. of characters in a JTextField by using Inputverifier class.
That's not what InputVerifier is for. You could use InputVerifier to prevent the field from losing focus if it has too many characters, but it won't actually prevent the user from typing in (or pasting in) too many characters.
To prevent the user from typing too many characters at all, you could try to use a KeyListener (as your code partially successfully does), or you could use a custom Document as Mr. Prime describes, but IMHO the easy way is to use a DocumentFilter.