• Post Reply Bookmark Topic Watch Topic
  • New Topic

Restricting characters in a JTextField

 
Jennifer Sohl
Ranch Hand
Posts: 455
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there! I have recently run across an issue that I need some help with. I have a custom text field that I created that limits the number of characters a user can key into a text field. The only problem with it, seems to be whenever someone copies text and pastes it into the text field, it doesn't cut it off at the set number of characters that is allowed. What changes do I need to make to make the "paste" function recognize the text field only takes a limited number of characters? Below is how I am currently limiting the text.



Thanks for any help!
 
Paul Clapham
Sheriff
Posts: 21892
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Am I correct in assuming that "fieldNumberChar" is the maximum number of characters you want to allow in the JTextField? If that is the case, then comparing the length of the new input to it is not what you want to do. After all usually that length is going to be 1.

You want to compare the result of inserting the new input to that number. So you would compare "getLength() + str.length()" to that number. But then shortening the input string to fit would be a difficult calculation, so you really need to calculate the amount of space left; that is "fieldNumberChar - getLength()". Then shorten the input string to that length.

Incidentally your code should fail even for regular typing, since that's the same as pasting a single character. If it doesn't, then you have an off-by-one error in your code somewhere. Or perhaps your code allows one extra character and your testing hasn't caught that yet.

Edit: to be absolutely correct, there are cases where str.toUpperCase() is longer than str, and you should take that into account in your code. But you are only going to encounter those cases if your users are typing their input in German.
[ October 22, 2007: Message edited by: Paul Clapham ]
 
Jennifer Sohl
Ranch Hand
Posts: 455
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Paul! Just wanted to let you know I did a bit more research on this after reading your post, and everything is working perfectly now! Thanks for taking the time to help me see the light!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!