Using DefaultFormatterFactory to control JFormattedTextField : DefaultFormatterFactory « Swing « Java Tutorial






Using DefaultFormatterFactory to control JFormattedTextField
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;

public class DefaultFormatterFactoryDemo {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Mask Input");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel label = new JLabel("Date");

    DateFormat displayFormat = new SimpleDateFormat("yyyy--MMMM--dd");
    DateFormatter displayFormatter = new DateFormatter(displayFormat);
    DateFormat editFormat = new SimpleDateFormat("MM/dd/yy");
    DateFormatter editFormatter = new DateFormatter(editFormat);
    DateFormat nullFormat = new SimpleDateFormat("'null'");
    DateFormatter nullFormatter = new DateFormatter(nullFormat);
    DefaultFormatterFactory factory = new DefaultFormatterFactory(displayFormatter,
        displayFormatter, editFormatter, nullFormatter);

    JFormattedTextField input = new JFormattedTextField(factory);
    input.setColumns(30);
    JPanel panel = new JPanel();
    panel.add(label);
    panel.add(input);
    frame.add(panel,"North");

    frame.add(new JTextField(),"Center");
    frame.pack();
    frame.setVisible(true);
  }
}








14.20.DefaultFormatterFactory
14.20.1.DefaultFormatterFactory Class
14.20.2.Using DefaultFormatterFactory to control JFormattedTextFieldUsing DefaultFormatterFactory to control JFormattedTextField