java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to use JFormattedTextField to format user input?

The JFormattedTextField allows us to create a text field that can accept a formatted input. In this example we create two formatted text fields that accept a valid phone number and date.

package com.javacoderanch.example.swing;

import javax.swing.*;
import javax.swing.text.MaskFormatter;
import javax.swing.text.DateFormatter;
import java.awt.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public class FormattedTextFieldExample extends JFrame {
    public FormattedTextFieldExample() {

    private void initComponents() {
        setSize(new Dimension(200, 200));
        getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

        MaskFormatter mask = null;
        try {
            // Create a MaskFormatter for accepting phone number, the # symbol accept
            // only a number. We can also set the empty value with a place holder
            // character.
            mask = new MaskFormatter("(###) ###-####");
        } catch (ParseException e) {

        // Create a formatted text field that accept a valid phone number.
        JFormattedTextField phoneField = new JFormattedTextField(mask);
        phoneField.setPreferredSize(new Dimension(100, 20));

        // Here we create a formatted text field that accept a date value. We
        // create an instance of SimpleDateFormat and use it to create a
        // DateFormatter instance which will be passed to the JFormattedTextField.
        DateFormat format = new SimpleDateFormat("dd-MMMM-yyyy");
        DateFormatter df = new DateFormatter(format);
        JFormattedTextField dateField = new JFormattedTextField(df);
        dateField.setPreferredSize(new Dimension(100, 20));
        dateField.setValue(new Date());


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new FormattedTextFieldExample().setVisible(true);

Here are some other characters that can be used in the MaskFormatter class.

# For number
? For letter
A For number or letter
* For anything
L For letter, it will be converted to the equivalent lower case
U For letter, it will be converted to the equivalent upper case
H For hexa decimal value
' To escape another mask character