001package jmri.util.swing;
002
003import java.text.ParseException;
004import java.util.regex.Matcher;
005import java.util.regex.Pattern;
006import java.util.regex.PatternSyntaxException;
007
008import javax.swing.text.DefaultFormatter;
009
010/**
011 * 
012 * From an early Java example, later at http://www.oracle.com/technetwork/java/reftf-138955.html#
013 *
014 * Example:
015 * new JFormattedTextField(new jmri.util.swing.RegexFormatter("[A-Za-z]\\d*"));
016 */
017public class RegexFormatter extends DefaultFormatter {
018    private Pattern pattern;
019    private Matcher matcher;
020
021    public RegexFormatter() {
022        super();
023    }
024
025    public RegexFormatter(String pattern) throws PatternSyntaxException {
026        this();
027        setPattern(Pattern.compile(pattern));
028    }
029
030    public RegexFormatter(Pattern pattern) {
031        this();
032        setPattern(pattern);
033    }
034
035    public void setPattern(Pattern pattern) {
036        this.pattern = pattern;
037    }
038
039    public Pattern getPattern() {
040        return pattern;
041    }
042
043    protected void setMatcher(Matcher matcher) {
044        this.matcher = matcher;
045    }
046
047    protected Matcher getMatcher() {
048        return matcher;
049    }
050
051    @Override
052    public Object stringToValue(String text) throws ParseException {
053        Pattern pattern = getPattern();
054
055        if (pattern != null) {
056            Matcher matcher = pattern.matcher(text);
057
058            if (matcher.matches()) {
059                setMatcher(matcher);
060                return super.stringToValue(text);
061            }
062            throw new ParseException("Pattern did not match", 0);
063        }
064        return text;
065    }
066}