Formatting with Regular Expressions

If you are a fan of regular expressions, you might be wondering whether Swing provides any direct support for using regular expressions with JFormattedTextFields. The answer is no. There is no direct support, but it’s easy to write your own formatter for regular expressions.

// RegexPatternFormatter.java -- formatter for regular expressions // import javax.swing.*; import javax.swing.text.*; public class RegexPatternFormatter extends DefaultFormatter { protected java.util.regex.Matcher matcher; public RegexPatternFormatter(java.util.regex.Pattern regex) { setOverwriteMode(false); matcher = regex.matcher(""); // Create a Matcher for the regular expression. } public Object stringToValue(String string) throws java.text.ParseException { if (string == null) return null; matcher.reset(string); // Set 'string' as the matcher's input. if (! matcher.matches( )) // Does 'string' match the regular expression? throw new java.text.ParseException("does not match regex", 0); // If we get this far, then it did match. return super.stringToValue(string); // Honors the valueClass property } public static void main(String argv[]) { // A demo main( ) method to show how RegexPatternFormatter could be used JLabel lab1 = new JLabel("even length strings:"); java.util.regex.Pattern evenLength = java.util.regex.Pattern.compile("(..)*"); JFormattedTextField ftf1 = new JFormattedTextField(new RegexPatternFormatter(evenLength)); JLabel lab2 = new JLabel("no vowels:"); java.util.regex.Pattern ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.