Channels ▼


Java: Better Interfaces via JFormattedTextField

Custom Formatters

If you have a data type that is variable in length and does not fit well with one of the existing formatter classes, or requires special rules for conversion, then you can create your own formatter class based on the DefaultFormatter class or any of the other Formatter classes (e.g. NumberFormatter). You will need to override the stringToValue and valueToString methods to provide the behavior you desire. stringToValue accepts a String as an input, parses it, and returns an Object. If the parsing is fails, then a ParseException should be thrown. The type of Object returned should match the results of getValueClass. The code necessary to parse the String will depend on the data you are parsing. If you are parsing a proper name, then your method may just check to see that the String is not empty and force the first letter to be capitalized. If you are parsing a URL or email address, then you'll want to employ a Pattern object to test the validity and sequence of the characters.

valueToString accepts an Object and converts it to a String. If the conversion fails, then a ParseException is thrown. The conversion may be as simple as calling the toString() method of the Object or the conversion may adjust the data before returning it. For example, a field that holds a percentage may want to store 5.3% as .053, but display it as 5.3%. In this case the valueToString method would multiply the value by 100, format it with the desired number of decimal places, then tag on the percent sign.

The EmailFormatter class extends the DefaultFormatter class and uses a precompiled pattern to check an email address.For more information on the email format and pattern matcher, see "How to Validate Email, SSN, Phone Numbers in Java Using Regular Expressions by Zaheer Paracha.

The code below creates a JFormattedTextField for entering an email address using class which you can download here.)

 JFormattedTextField emailField = new JFormattedTextField();
 EmailFormatter emailFormatter = new EmailFormatter();
 DefaultFormatterFactory emailFormatterFactory = 
                new DefaultFormatterFactory(emailFormatter);

If you want a custom formatter that handles numbers, then you should create a class that extends NumberFormatter. The PercentFormatter class extends NumberFormatter to create a class to handle percentage data. The constructor accepts a NumberFormat object to handle formatting and parsing. The valueToString method first multiplies the value by 100, then calls super class's valueToString method, finally a percent is added and the String returned. The stringToValue first strips off any extra white space or percent signs, then converts to a double using the super class's stringToValue method, divides by 100, then returns a Double object. In this way the value is stored in a form amenable to using in calculations, but displayed in a manner the user expects.

The code below creates a JFormattedTextField for entering an percent using which you can download here.

    JFormattedTextField percentField = new JFormattedTextField();
    PercentFormatter percentFormatter = 
               new PercentFormatter(new DecimalFormat("#.##"));
    DefaultFormatterFactory percentFormatterFactory = 
               new DefaultFormatterFactory(percentFormatter);

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.