How do I use JFormattedTextField to format user input?

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

package org.kodejava.swing;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.DateFormatter;
import javax.swing.text.MaskFormatter;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormattedTextFieldExample extends JFrame {
    public FormattedTextFieldExample() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new FormattedTextFieldExample().setVisible(true));
    }

    private void initComponents() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("Format User Input");
        setSize(new Dimension(500, 500));
        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("(###) ###-####");
            mask.setPlaceholderCharacter('_');
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 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());

        getContentPane().add(phoneField);
        getContentPane().add(dateField);
    }
}
User Input Format

User Input Format

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

Char Description
# 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 hexadecimal value
To escape another mask character