Formatted Masked Input: new MaskFormatter((###)###-####) (For phone number) : JFromattedField MaskFormatter « Swing « Java Tutorial






Formatted Masked Input: new MaskFormatter((###)###-####) (For phone number)
import java.text.ParseException;

import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;

public class MaskInputSample2 {
  public static void main(String args[]) {

    JFrame frame = new JFrame("Mask Input");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel label;
    JFormattedTextField input;
    JPanel panel;
    MaskFormatter formatter;

    BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
    frame.setLayout(layout);

    try {
      label = new JLabel("SSN");
      formatter = new MaskFormatter("'(###')' ###'-####");
      input = new JFormattedTextField(formatter);
      input.setValue("(123) 145-6789");
      input.setColumns(20);
      panel = new JPanel();
      panel.add(label);
      panel.add(input);
      frame.add(panel);
    } catch (ParseException e) {
      System.err.println("Unable to add SSN");
    }
    frame.pack();
    frame.setVisible(true);
  }
}








14.19.JFromattedField MaskFormatter
14.19.1.Input Masks Summary Table
14.19.2.Formatted Masked Input: new MaskFormatter(###-##-####)Formatted Masked Input: new MaskFormatter(###-##-####)
14.19.3.Formatted Masked Input: new MaskFormatter((###)###-####) (For phone number)Formatted Masked Input: new MaskFormatter((###)###-####) (For phone number)
14.19.4.Regex Formatter with a JFormattedTextFieldRegex Formatter with a JFormattedTextField
14.19.5.Work with DefaultFormatterFactory
14.19.6.Apply a mask to String