Java Swing How to - Create custom java.text.Format for JFormattedTextField








Question

We would like to know how to create custom java.text.Format for JFormattedTextField.

Answer

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;
import java.awt.FlowLayout;
import java.text.AttributedCharacterIterator;
import java.text.FieldPosition;
import java.text.Format;
import java.text.NumberFormat;
import java.text.ParsePosition;
//from   w  w  w. j av  a  2 s  .c  om
public class Main {
  public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(100, 75);
    JPanel content = new JPanel(new FlowLayout());
    frame.setContentPane(content);

    MaskFormatter formatter = new MaskFormatter("#");
    formatter.setValidCharacters("123456789");

    JFormattedTextField f1 = new JFormattedTextField(formatter);
    f1.setValue(null);
    f1.setColumns(1);

    content.add(f1);
    frame.setVisible(true);
  }

  private static Format createFormat() {
    NumberFormat format = NumberFormat.getInstance();
    format.setParseIntegerOnly(true);
    return new Format() {
      @Override
      public StringBuffer format(Object obj, StringBuffer toAppendTo,
          FieldPosition pos) {
        return format.format(obj, toAppendTo, pos);
      }

      @Override
      public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
        return format.formatToCharacterIterator(obj);
      }

      @Override
      public Object parseObject(String source, ParsePosition pos) {
        int initialIndex = pos.getIndex();
        Object result = format.parseObject(source, pos);
        if (result != null && pos.getIndex() > initialIndex + 1) {
          int errorIndex = initialIndex + 1;
          pos.setIndex(initialIndex);
          pos.setErrorIndex(errorIndex);
          return null;
        }
        return result;
      }
    };
  }
}