JFormattedTextField can have four types of formatters - Java Swing

Java examples for Swing:JFormattedTextField

Introduction

A null formatter: used when the value in the field is null.

An edit Formatter: used when the field has focus.

A display Formatter: used when the field does not have focus and it has a non-null value.

A default Formatter: used in the absence of any of the above three formatters.

The following code create a JFormattedTextField with four types of formatters.

Demo Code

import java.text.SimpleDateFormat;

import javax.swing.JFormattedTextField;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;

public class Main {

  public static void main(String[] args) {
    DateFormatter df = new DateFormatter(new SimpleDateFormat("mmmm dd, yyyy"));
    DateFormatter edf = new DateFormatter(new SimpleDateFormat("mm/dd/yyyy"));
    DefaultFormatterFactory ddf = new DefaultFormatterFactory(df, df, edf, df);

    JFormattedTextField ssnField = null;
    ssnField.setFormatterFactory(ddf);/*w  ww  .ja v a2s  .c  om*/

  }
}

Related Tutorials