1 package nl.tudelft.simulation.dsol.swing.gui.util;
2
3 import java.text.ParseException;
4 import java.util.regex.Matcher;
5 import java.util.regex.Pattern;
6
7 import javax.swing.text.DefaultFormatter;
8
9 /**
10 * Extension of a DefaultFormatter that uses a regular expression. <br>
11 * Derived from <a href="http://www.java2s.com/Tutorial/Java/0240__Swing/RegexFormatterwithaJFormattedTextField.htm">
12 * http://www.java2s.com/Tutorial/Java/0240__Swing/RegexFormatterwithaJFormattedTextField.htm</a>
13 * <p>
14 * Copyright (c) 2020-2023 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
15 * for project information <a href="https://simulation.tudelft.nl/dsol/manual/" target="_blank">DSOL Manual</a>. The DSOL
16 * project is distributed under a three-clause BSD-style license, which can be found at
17 * <a href="https://https://simulation.tudelft.nl/dsol/docs/latest/license.html" target="_blank">DSOL License</a>.
18 * </p>
19 * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
20 */
21 public class RegexFormatter extends DefaultFormatter
22 {
23 /** */
24 private static final long serialVersionUID = 20141212L;
25
26 /** The regular expression pattern. */
27 private Pattern pattern;
28
29 /**
30 * Create a new RegexFormatter.
31 * @param pattern String; regular expression pattern that defines what this RexexFormatter will accept
32 */
33 public RegexFormatter(final String pattern)
34 {
35 this.pattern = Pattern.compile(pattern);
36 }
37
38 @Override
39 public Object stringToValue(final String text) throws ParseException
40 {
41 Matcher matcher = this.pattern.matcher(text);
42 if (matcher.matches())
43 {
44 return super.stringToValue(text);
45 }
46 throw new ParseException("Pattern did not match", 0);
47 }
48
49 /** {@inheritDoc} */
50 @Override
51 public String toString()
52 {
53 return "RegexFormatter [pattern=" + this.pattern + "]";
54 }
55 }