Set place holder char for JFormattedTextField in Java

Description

The following code shows how to set place holder char for JFormattedTextField.

Example


import java.awt.Container;
import java.text.ParseException;
// w w  w.  ja va2s . co m
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.text.MaskFormatter;

public class Main {
  public static void main(String args[]) throws ParseException {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = f.getContentPane();
    content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));

    MaskFormatter mf1 = new MaskFormatter("###-###-###");
    mf1.setPlaceholderCharacter('_');
    JFormattedTextField ftf1 = new JFormattedTextField(mf1);
    content.add(ftf1);

    MaskFormatter mf2 = new MaskFormatter("(###) ###-####");
    JFormattedTextField ftf2 = new JFormattedTextField(mf2);
    content.add(ftf2);
    f.setSize(300, 100);
    f.setVisible(true);
  }
}

The code above generates the following result.

Set place holder char for JFormattedTextField in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer