Swing Examples - Create a Masked TextField



Following example showcase how to create and show a masked text field in swing based application.

We are using the following APIs.

  • JFormattedTextField − To create a formatted text field.

  • MaskFormatter − To create a formatter to allows only characters specified in the pattern passed to MaskFormatter.

Example

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.text.ParseException;

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

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

     JLabel zipLabel = new JLabel("Zip Code");
     JFormattedTextField zipTextField = null;
      try {
         zipTextField = new JFormattedTextField(
            new MaskFormatter("#####")); 
         zipTextField.setColumns(5);
      } catch (ParseException e) {
         e.printStackTrace();
      }

      zipLabel.setLabelFor(zipTextField);
      
      panel.add(zipLabel);
      panel.add(zipTextField);

      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }  
}

Output

Create a Masked TextField

Here we've used "#####" as pattern signifying that only numbers are allowed in the text fields, no other characters can be entered. And we can not enter more than 5 numbers. Following is the list of patterns to control characters.

Sr. No. Character & Description
1 #

Any digit.

2 '

Escape character, to escape special formatting characters.

3 U

Any character. Will be converted to Upper case.

4 L

Any character. Will be converted to Lower case.

5 A

Any character or number.

6 ?

Any character.

7 *

Anything.

8 H

Any hex character (0-9, a-f or A-F).

swingexamples_formatted_textfields.htm
Advertisements