This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes Custom Formats JFormattedTextField Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Custom Formats JFormattedTextField" Watch "Custom Formats JFormattedTextField" New topic

Custom Formats JFormattedTextField

Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
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.


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:


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

Joined: Jun 09, 2003
Posts: 4632
this might work

[ June 23, 2005: Message edited by: Michael Dunn ]
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
Thanks I'll try that when I get home.
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
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.
It is sorta covered in the JavaRanch Style Guide.
subject: Custom Formats JFormattedTextField
It's not a secret anymore!