Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Custom Formats JFormattedTextField

 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm wondering if anybody knows how to write a custom formatter for a JFormattedTextField. There are a few I want to do, but I'll just mention the easiest.

ZipFormatter:

It should allow the entry of a 5 digit zip, a 9 digit zip, or nothing. When typing the user should see input like this:

1
12
123
1234
12345
12345-6
12345-67
12345-678
12345-6789

So the '-' should only appear if the zip is longer than 5 digits.

I tried subclassing DefaultFormatter and overriding the two abstract methods stringToValue and valueToString, but that doesn't work.

Thanks in advance for any help.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this might work


[ June 23, 2005: Message edited by: Michael Dunn ]
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks I'll try that when I get home.
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what I came up with. It seems to work pretty well. This is not pretty code and is not really what I would consider the 'correct' way of doing it. I should be overriding the other methods (two replace methods, and the remove method), but that seems to get a bit complicated. So for now this works.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic