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.
How can we set the maximum input string length of JTextField? I hope that user can type in at most 10 characters in the JTextField. JTextFiled t1 = new JTextField(10); t1.setColumns(10); But when the application runs, user can still type in more than 10 characters. What should I do? Thanks to any suggestions.
Bartenders: Shan Chen is currently doing the SCJD assignment, and this question looks like it is related to that assignment ... do you want to move this thread? Hi Shan, You may be able to do this by extending JTextField and extending PlainDocument to set a custom editor. There is a tutorial on this somewhere, let me see.... Take a look at Sun tutorial on creating text fields ... the section on creating a validated text field. Regards, Andrew
Hi, Andrew, Thanks for your help. A validated textfield is to check the input after user has typed in something. What I wish to get is that user can not type in any character after 10 characters. Like 'input' in html: <input name="tf" value="tf" maxlength=10 ... > I will read the paper you mentioned anyway. Thanks. Shan
author and jackaroo
Hi Shan, What I suggested can be used to validate on the fly.
The data in a change-validated field is checked each time the field changes. A field that is change-validated can never contain invalid data because every change (keystroke, cut, copy, and so on) that might cause the data to be invalid is rejected.
I have used this to create a field in my application that will only allow numeric inputs. It refuses to allow any other character to be entered. From memory of how this works, I think you should be able to put a size limit on the field as well. Regards, Andrew [ May 19, 2003: Message edited by: Andrew Monkhouse ]
Joined: Apr 09, 2003
Hi, Andrew, The method you mentioned should be able to slove the problem. But the code is a little bit complicated. I have posted the same topic in SCJD forum to see if there is any simplier way, or maybe no other ways. Thank you.