Channels ▼
RSS

Design

Java: Better Interfaces via JFormattedTextField


Data quality and accuracy is key to success for every application. Databases full of invalid phone numbers, improperly formatted email addresses, or out of range numeric data are of no use to anyone. Java Swing interface programmers know all too well the work involved in error checking user inputs taken from vanilla JTextFields. Many probably have been tempted to implement interfaces using JFormattedTextFields, but have been put off by the complexity of masks, formatters, verifiers, abstract classes, and interfaces that are required. In this article, I explain the proper use of the JFormattedTextFieldand its related classes to create forms that provide both guided input for users and validated data for the application. The source code for a sample application and a library of reusable classes for common data entry items based on JFormattedTextField is available for download here.

JFormattedTextFields are alternatives to JTextFields that are well worth using. They differ from JTextFields in several ways:

  • First, they maintain a current "value" associated with the field as an Object. The getValue and setValue methods are provided to access it.
  • Second, they use formatter objects to control the display of the value. One formatter is used to convert the value object to a String for display when the field does not have the focus; a separate formatter is used to convert the value when it receives the focus. Therefore a field that holds currency can limit the number of decimal places shown, have a dollar sign, and have commas separating the thousands while it is not being changed, then automatically change to a form with just digits and decimals when the focus is shifted to it. A type of formatter called a MaskFormatter can provide a "type-in-the-blank" template to guide the users input. MaskFormatters are useful for data types such as phone numbers, dates, and Social Security Numbers.
  • The third, and most important difference is that when combined with InputVerifiers they can handle all the parsing, range checking, and formatting required for processing GUI form interfaces. For example, Figure 1(a) shows a JFormattedTextField used to input currency with the focus, Figure 1(b) shows the same JFormattedTextField without the focus. Table 1 compares the code required to input, convert, and validate a double value using JTextField and JFormattedTextField.


Figure 1(a)


Figure 1(b)


Table 1: Comparison of code to access JTextField and JFormattedTextField values.

Implementing a JFormattedTextField

According to the Java API:

"JFormattedTextField does not do the formatting it self, rather formatting is done through an instance of JFormattedTextField.AbstractFormatter which is obtained from an instance of JFormattedTextField.AbstractFormatterFactory."

What this really means is that to make a JFormattedTextField operate you need to create an instance of an AbstractFormatterFactory. The easiest way to do this is to use a convenience class called DefaultFormatterFactory, then attach it to the JFormattedTextField. The primary purpose of the DefaultFormatterFactory is to maintain three AbstractFormatter classes for the JFormattedTextField. One abstract formatter is the default formatter, it is used if a more specific formatter cannot be found; another is the display formatter used to format the value when the JFormattedTextField does not have the focus; and the third is the edit formatter, used to format the value when the JFormattedTextField has the focus.


DefaultFormatterFactory dff = 
       new DefaultFormatterFactory(defFormatter, displayFormatter, editFormatter);
JFormattedTextField tf = new JFormattedTextField(dff);

The formatter classes are primarily responsible for providing the body for two methods, stringToValue and valueToString. stringToValue parses a String and creates an object of the proper type (Long, Double, Date, Integer, etc). valueToString takes the current value and formats it for display. AbstractFormatter classes may in turn rely on specific format classes such as DecimalFormat and SimpleDateFormat. Creating formatter classes from scratch can be a daunting task, fortunately, the standard Java API provides numerous formatter classes that can be used as is. The standard class you use is determined by the type of data you need to format. Numeric data (currencies, counts, salaries) should use the NumberFormatter class, fixed length string data should use the MaskFormatter class (social security numbers, credit card numbers, phone numbers, dates), and variable length string data will need to have a custom formatter created based on the DefautFormatter class.

NumberFormatter

A NumberFormatter can be used for any numeric field, age, income, annual rainfall, quantity, cost, etc. A NumberFormatter object is created using a constructor that accepts an object of type NumberFormat as its only parameter. Typically a DecimalFormat object (subclass of NumberFormat) is used. For example:


NumberFormatter currencyFormatter = 
        new NumberFormatter(new DecimalFormat("$ #,###.00")); 

In the above example, a DecimalFormat object is specified that can take a numeric value and convert it to a String using the specified pattern. The "#" character is replaced with a digit (or absent if 0), the "0" is replaced with a digit. The fact that there are only two "0" to the right of the decimal point indicates only two decimal places are to be shown (rounding up/down automatically). The "," acts as a grouping separator. Since there are three "#" between the decimal point and the comma, the numbers to the left of the decimal will be grouped in sets of three. You only need to specify the position of the first grouping separator.

The example above adds the grouping separator and dollar sign. Both of these will cause parse errors when converting back to a number. Therefore, you will typically need a separate NumberFormatter for the edit and display formats. The one used for the edit format would exclude the dollar sign, grouping separator (comma), and use "#"s to the right of the decimal. For example:


NumberFormatter displayCurrencyFormatter = 
        new NumberFormatter(new DecimalFormat("$ #,###.00")); 
NumberFormatter editCurrencyFormatter = 
        new NumberFormatter(new DecimalFormat("#.##")); 

The getValue method of the JFormattedTextField calls the parse method within the DecimalFormat class, and may return a Long or a Double, depending on the String involved. If the String has a decimal in it, a Double is returned, if it doesn't, a Long is returned. To make the class of the return value more predictable (and avoid class cast exceptions), you should call the setValueClass method and specify whether you want a Long, Double, Float, Short, Byte, or Integer; for example:


displayCurrencyFormatter.setValueClass(Double.class);
editCurrencyFormatter.setValueClass(Double.class);

The following is a complete example for creating a JFormattedTextField for entering salary:


// create the JFormattedTextField
   JFormattedTextField salaryField = new JFormattedTextField();  
// create the formatters, default, display, edit
   NumberFormatter defaultFormatter = new NumberFormatter(new DecimalFormat("#.##"));
   NumberFormatter displayFormatter = 
       new NumberFormatter(new DecimalFormat("$ #,###.00"));
   NumberFormatter editFormatter = new NumberFormatter(new DecimalFormat("#.##")); 
// set their value classes
   defaultFormatter.setValueClass(Double.class);
   displayFormatter.setValueClass(Double.class);
   editFormatter.setValueClass(Double.class);   
// create and set the DefaultFormatterFactory
   DefaultFormatterFactory salaryFactory = 
       new DefaultFormatterFactory(defaultFormatter,displayFormatter,editFormatter);
   salaryField.setFormatterFactory(salaryFactory);

MaskFormatter

The MaskFormatter is best used to format Strings that have a fixed length and set format. Examples include: dates, Social Security Numbers, phone numbers, credit-card numbers, ZIP codes, vehicle ID numbers (VINs). MaskFormatters are not suitable for Strings with variable numbers of characters, e.g. URLs and email addresses. A single instance of the MaskFormatter can be used for both the edit and display formats of an AbstractFormatterFactory. A MaskFormatter object is created using a constructor that accepts a formatting mask as its only parameter. The formatting mask specifies what type of characters can appear in each position and any literal characters. Literal characters are fixed in place and are not changeable by the users; for example, the dash and parenthesis in a phone number would be considered literal characters. Table 2 shows the different mask characters used by the MaskFormatter.


Table 2: MaskFormatter Characters.

For example, the mask "###-##-####" could be used for a Social Security number. The #s allow the user to type in any number, the dashes are literals and fixed in place. Similarly for a ZIP code the mask "#####-####" could be used:


MaskFormatter zipMask = new MaskFormatter("#####-####");
MaskFormatter ssnMask = new MaskFormatter("###-##-####");

You can restrict what the user types in even more by invoking the setValidCharacters or the setInvalidCharacters method. For example, if you wanted to restrict the digits in a ZIP code to just 2s and 3s, then you could make the following call:


zipMask.setValidCharacters("23");  // only allow 2, 3 in the zip code

Alternatively, if you wanted any digit but a 2 or a 3 then you could make the following call:


zipMask.setInvalidCharacters("23"); // don't allow 2,3 in the zip code.

A final consideration when creating a MaskFormatter is setting the placeholder character. This character is inserted into the String if the current value has too few characters or when the user presses the delete or backspace keys while editing. It is common to use an underscore as the placeholder, but any character will do. To avoid confusion, select a character that is not used as a literal or valid character in the mask. To set the placeholder, call the setPlaceholderCharacter method; for example:


zipMask.setPlaceholderCharacter('_');  // use an underscore as a placeholder

The Table 3 provides a few common masks.


Table 3: Masks for common data types.

(You may want to consider using a fixed-width font (such as Courier) for the JFormattedTextField. This makes the overall appearance and character spacing more pleasing to the eye.

The example below creates a JFormattedTextField for entering a Date:


 // create a MaskFormatter for Dates
 JFormattedTextField dateField = new JFormattedTextField();
 MaskFormatter dateFormatter = new MaskFormatter("##/##/#### ##:##:## UM");
 dateFormatter.setValidCharacters("0123456789AP");
 dateFormatter.setPlaceholderCharacter('_');     
 dateFormatter.setValueClass(String.class);   
 DefaultFormatterFactory dateFormatterFactory = new 
          DefaultFormatterFactory(dateFormatter);
 dateField.setFormatterFactory(dateFormatterFactory);

The example below creates a JFormattedTextField for entering a Social Security number:


JFormattedTextField ssnField = new JFormattedTextField();
MaskFormatter ssnFormatter = new MaskFormatter("###-##-####");
ssnFormatter.setValueClass(String.class);
ssnFormatter.setPlaceholderCharacter('_');  
DefaultFormatterFactory ssnFormatterFactory = new 
          DefaultFormatterFactory(ssnFormatter);
ssnField.setFormatterFactory(ssnFormatterFactory);


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.
 

Video