Java Swing DefaultFormatter create Regex based formatter

Description

Java Swing DefaultFormatter create Regex based formatter

import java.awt.BorderLayout;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.DefaultFormatter;

public class Main {
   public static void main(final String args[]) throws Exception {
      JFrame frame = new JFrame("Formatted Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      JFormattedTextField input = new JFormattedTextField(new RegexFormatter("[0-9]"));
      input.setValue("123123");

      frame.add(input, BorderLayout.NORTH);

      frame.add(new JTextField(), BorderLayout.SOUTH);
      frame.setSize(250, 100);//  w w w.j a va2s.co m
      frame.setVisible(true);
   }
}

class RegexFormatter extends DefaultFormatter {
   private Pattern pattern;

   private Matcher matcher;

   public RegexFormatter() {
      super();
   }

   public RegexFormatter(String pattern) throws PatternSyntaxException {
      this();
      setPattern(Pattern.compile(pattern));
   }

   public RegexFormatter(Pattern pattern) {
      this();
      setPattern(pattern);
   }

   public void setPattern(Pattern pattern) {
      this.pattern = pattern;
   }

   public Pattern getPattern() {
      return pattern;
   }

   protected void setMatcher(Matcher matcher) {
      this.matcher = matcher;
   }

   protected Matcher getMatcher() {
      return matcher;
   }

   public Object stringToValue(String text) throws ParseException {
      Pattern pattern = getPattern();

      if (pattern != null) {
         Matcher matcher = pattern.matcher(text);

         if (matcher.matches()) {
            setMatcher(matcher);
            return super.stringToValue(text);
         }
         throw new ParseException("Pattern did not match", 0);
      }
      return text;
   }
}



PreviousNext

Related