Using MaskFormatter in JFormattedTextField

The following example illustrates using MaskFormatter in JFormattedTextField to restrict the user to type a phone number. The advantage with a MaskFormatter is that the user cannot even type against the format specified in it. For example, in the following program, the user will only be able to enter numbers but and that to only 12. He cannot type more than that, and if he types less than that and hits enter. In this example, you'll learn..
  1. How to create a mask formatter?
  2. How to use it with JFormattedTextField?
  3. What is setPlaceholderCharacter() and how to use it?
import javax.swing.*;
import java.awt.*;
import javax.swing.text.*;
class MaskFormatterExample1 extends JFrame
{
JFormattedTextField t;
MaskFormatter m;

    public MaskFormatterExample1()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Mask formatter Example");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
       
        // A phone number formatter
        // (country code)-(area code)-(number)
        try
        {
        m=new MaskFormatter("##-###-#######");
        m.setPlaceholderCharacter('#');
        t=new JFormattedTextField(m);
        t.setColumns(12);
        add(t);
        }catch(Exception e){}
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new MaskFormatterExample1();
    }
}

new MaskFormatter("##-###-#######"); This creates a MaskFormatter object where # represents a number and hyphen here separates country, area codes and phone number.
setPlaceholderCharacter(): This method sets the place holder character that appears in the place of digits that aren't entered. You will understand when you see it in practical.

MaskFormatter with JFormattedTextField
 
“Do not go where the path may lead; go instead where there is no path and leave a trail” - Ralph Waldo Emerson

No comments: