Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Magic with Merlin: Swing's new JFormattedTextField component

Learn to create input fields that accept formatted text with minimal work

John Zukowski (jaz@zukowski.net), President, JZ Ventures, Inc.
Author photo
John Zukowski conducts strategic Java consulting with JZ Ventures, Inc. and serves as the resident guru for a number of jGuru's community-driven Java FAQs. His latest books are Mastering Java 2, J2SE 1.4 and Learn Java with JBuilder 6. Reach John at jaz@zukowski.net.

Summary:  Accepting formatted input doesn't have to be difficult with input verifiers and focus listeners. In this installment of Magic with Merlin, John shows you how to use the new JFormattedTextField component to prompt for numbers, dates, and formatted input.

View more content in this series

Date:  01 Jun 2002
Level:  Introductory
Also available in:   Japanese

Activity:  22715 views
Comments:  

The Java 2 Standard Edition (J2SE), version 1.4, adds two new Swing components to the palette of available GUI elements: JSpinner and JFormattedTextField. We covered the JSpinner component in the very first Magic with Merlin column; we'll now explore JFormattedTextField.

While the JFormattedTextField component looks like JTextField, it acts completely different. In the simplest case, you can provide an input mask like "(###) ###-####" for a telephone number, and it will not accept any input that doesn't follow that format. In more complicated cases, there is both a display formatter and an input formatter. For example, the default date formatter permits scrolling through the available months or days based upon where the cursor is located while editing.

When working with JFormattedTextField, acceptable input is either explicitly specified by the mask or specified by a value for the component. In the latter case, the component uses the Factory design pattern to look up the default formatters for the class of the specified value. The DefaultFormatterFactory component comes with preinstalled formatters for dates, numbers, java.text.Format subclasses, and a catchall formatter for everything else.

Let's look at how to work with the component.

Configuring acceptable input

Masked input is typically configured by using an instance of the MaskFormatter class. Found in the javax.swing.text package, MaskFormatter works by using a series of characters to designate acceptable input. Each of the eight characters in the series represents one character in the input, as listed below:

#A number
?A letter
AA letter or number
*Anything
UA letter, with lowercase characters mapped to their uppercase equivalents
LA letter, with uppercase characters mapped to their lowercase equivalents
HA hexadecimal digit (A-F, a-f, 0-9)
'Used to escape another mask character

In addition to MaskFormatter, you can use the DateFormat and NumberFormat classes from the java.text package to specify the input format. Listing 1 shows some possible formats.

// Four-digit year, followed by month name and day of month,
// each separated by two dashes (--)
DateFormat format = 
  new SimpleDateFormat("yyyy--MMMM--dd");
DateFormatter df = new DateFormatter(format);
// US Social Security number
MaskFormatter mf1 = 
  new MaskFormatter("###-##-####");
// US telephone number
MaskFormatter mf2 = 
  new MaskFormatter("(###) ###-####");

Once you've specified the input format, you would then pass the formatter into the JFormattedTextField constructor, as shown below:

JFormattedTextField ftf1 = new 
      JFormattedTextField(df);

Depending on the formatter used, there are other configurable options. For instance, with MaskFormatter, you can set the placeholder character with setPlaceholderCharacter(char). Also, for date fields, it helps if you initialize the field to some value so a user will know what input format is acceptable.


Putting it all together

That's really all there is to creating masked input fields. Listing 2 provides a complete example for you to try out the new capabilities by combining the previous code snippets. Figure 1 shows the display. Feel free to adjust the individual masks to try out the other mask characters.


Figure 1. JFormattedTextField in action
JFormattedTextField in action
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.util.*;
import java.text.*;

public class FormattedSample {
  public static void main (String args[]) throws ParseException {
    JFrame f = new JFrame("JFormattedTextField Sample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = f.getContentPane();
    content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
    // Four-digit year, followed by month name and day of month,
    // each separated by two dashes (--)
    DateFormat format = 
      new SimpleDateFormat("yyyy--MMMM--dd");
    DateFormatter df = new DateFormatter(format);
    JFormattedTextField ftf1 = new 
      JFormattedTextField(df);
    ftf1.setValue(new Date());
    content.add(ftf1);
    // US Social Security number
    MaskFormatter mf1 = 
      new MaskFormatter("###-##-####");
    mf1.setPlaceholderCharacter('_');
    JFormattedTextField ftf2 = new 
      JFormattedTextField(mf1);
    content.add(ftf2);
    // US telephone number
    MaskFormatter mf2 = 
      new MaskFormatter("(###) ###-####");
    JFormattedTextField ftf3 = new 
      JFormattedTextField(mf2);
    content.add(ftf3);
    f.setSize(300, 100);
    f.show();
  }
}


Resources

About the author

Author photo

John Zukowski conducts strategic Java consulting with JZ Ventures, Inc. and serves as the resident guru for a number of jGuru's community-driven Java FAQs. His latest books are Mastering Java 2, J2SE 1.4 and Learn Java with JBuilder 6. Reach John at jaz@zukowski.net.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=10675
ArticleTitle=Magic with Merlin: Swing's new JFormattedTextField component
publish-date=06012002
author1-email=jaz@zukowski.net
author1-email-cc=jaloi@us.ibm.com