Java Swing How to - Create custom mask for JFormattedTextField








Question

We would like to know how to create custom mask for JFormattedTextField.

Answer

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.text.MaskFormatter;
/*  ww w . ja va  2  s.  com*/
public class Main {
    String formatString = "##/######";
    MaskFormatter formatCNP = createFormatter(formatString);
    JFormattedTextField jtfCNP = new JFormattedTextField(formatCNP);
    JFrame frame = new JFrame("MaskFormatter Test");
    public Main() {
        jtfCNP.setColumns(20);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(jtfCNP);
        frame.pack();
        frame.setVisible(true);
    }

    MaskFormatter createFormatter(String format) {
        MaskFormatter formatter = null;
        try {
            formatter = new MaskFormatter(format);
            formatter.setPlaceholderCharacter('.'/*or '0' etc*/);
            formatter.setAllowsInvalid(false); // if needed
            formatter.setOverwriteMode(true); // if needed
        } catch (java.text.ParseException exc) {
            System.err.println("formatter is bad: " + exc.getMessage());
        }
        return formatter;
    }

    public static void main(String[] args) {
new Main();
     
    }
}