Java Swing How to - Create custom JFormattedTextField specific format








Question

We would like to know how to create custom JFormattedTextField specific format.

Answer

import java.awt.BorderLayout;
//from  ww  w.jav a2  s .  co m
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;

public class Main extends JPanel {

  private JFormattedTextField  formatText = new JFormattedTextField(createFormatter("##:##"));

  public Main() {
    formatText.setColumns(20);
    formatText.setText("00:00");

    setLayout(new BorderLayout());
    add(new JLabel("Enter only numbers"), BorderLayout.NORTH);
    add(formatText, BorderLayout.CENTER);
  }

  private MaskFormatter createFormatter(String s) {
    MaskFormatter formatter = null;
    try {
      formatter = new MaskFormatter(s);
    } catch (java.text.ParseException exc) {
      System.err.println("formatter is bad: " + exc.getMessage());
    }
    return formatter;
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new Main());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}