File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion 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.
I agree. Here's the link:
subject: Custom Formats JFormattedTextField
It's not a secret anymore!