Java Swing How to - Create JFormattedTextField with MaskFormatter and DateFormat








Question

We would like to know how to create JFormattedTextField with MaskFormatter and DateFormat.

Answer

import java.awt.GridLayout;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/* w w w .j  av  a2s. c  o  m*/
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.text.MaskFormatter;

public class Main {
  public static void main(String[] args) throws Exception {
    final MaskFormatter formatter = new TimeFormatter(); 
    formatter.setValueClass(java.util.Date.class);
    final JFormattedTextField tf2 = new JFormattedTextField(formatter);
    tf2.setValue(new Date()); 
    final JLabel label = new JLabel();
    JButton bt = new JButton("Show Value");
    bt.addActionListener(e->{
        System.out.println(" value 2 = " + tf2.getValue());
        System.out.println(" value 2 = " + tf2.getText());
        System.out.println("value class: " + formatter.getValueClass());
        label.setText(tf2.getText());
    });
    JFrame f = new JFrame();
    f.getContentPane().setLayout(new GridLayout());
    f.getContentPane().add(tf2);
    f.getContentPane().add(label);
    f.getContentPane().add(bt);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setVisible(true);
  }
}

class TimeFormatter extends MaskFormatter {
  public TimeFormatter() {
    try {
      setMask("##/##/####");
      setPlaceholderCharacter('0');
      setAllowsInvalid(false);
      setOverwriteMode(true);
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
  @Override
  public Object stringToValue(String string) throws ParseException {
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    if (string == null) {
      string = "00/00/0000";
    }
    return df.parse(string);
  }
  @Override
  public String valueToString(Object value) throws ParseException {
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    if (value == null) {
      value = new Date(0);
    }
    return df.format((Date) value);
  }
}