Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

set maximum input length of JTextField

 
shan chen
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, all,

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.
 
Andrew Monkhouse
author and jackaroo
Marshal Commander
Pie
Posts: 11854
185
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
shan chen
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Andrew Monkhouse
author and jackaroo
Marshal Commander
Pie
Posts: 11854
185
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
shan chen
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic