Core Java Books

Wednesday, 2 March 2011

JTextFields and Regex Documents

I had planned on writing a post about auto complete JCheckBoxes but before this I've decided to jot down some notes on a simple regular expression document class I've written for handling text entry on text fields.

As they say there are many ways to skin a cat and this is just a simple way for me to restrict the number of characters entered into a fields and also the characters that can be typed by making use of a regular expression. I know there are other ways of doing this but I think this offers a nice example of what you can start doing with Document classes and how useful they can be. To get really fancy you could also investigate the JFormattedText component and see how you can restrict user input and focus traversal but for now I will comment on JTextField and keep things light.

In the examples I allow a user to enter a 'Caller Number', 10 characters are allowed. The characters can be any mixture of digits, space, + or -. They can also enter a 'Caller Code' and here they are allowed to enter up to 2 characters which can be A to E or 1 to 7.

The regex expressions used are:

"[0-9 \\-\\+]+"

and

"[A-E1-7]"

Try it out:




(Java 1.6 required!)

I achieved this by extending the Document class with a MaxLengthDocument class that restricts the number of characters than can be entered. I then extended the MaxLengthDocument class with RegexDocument class which makes use of the Matcher and Pattern classes in the Regex package.

I simply set the Document on  the two JTextField's, for example:

callerNumberTF.setDocument(new RegexDocument("[0-9 \\-\\+]+", 10));

See the code below.

The MaxLengthDocument:



package com.webbyit.swing;

import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * Simple Document class that restricts input on the associated text field to a
 * specified maximum length.
 *
 @author webbyit
 *
 */
public class MaxLengthDocument extends PlainDocument {

    /**
     * Maximum length of the text
     */
    private final int maxLength;

    /**
     * Default constructor.
     *
     @param maxLength
     *            the maximum number of characters that can be entered in the
     *            field
     */
    public MaxLengthDocument(final int maxLength) {
        super();
        this.maxLength = maxLength;
    }

    @Override
    public void insertString(final int offset, final String str,
                             final AttributeSet attrthrows BadLocationException {
        if (getLength() + str.length() > maxLength) {
            Toolkit.getDefaultToolkit().beep();
            return;
        }
        super.insertString(offset, str, attr);
    }
}

The RegexDocument:



package com.webbyit.swing;

import java.awt.Toolkit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;

/**
 * Class to provide restriction on user input using a regex pattern.
 *
 @author webbyit
 *
 */
public class RegexDocument extends MaxLengthDocument {

    protected final Pattern pattern;

    /**
     * Contructor used to construct a document object which pattern matches
     * strings as typed.
     *
     @param regex
     *            pattern to match on typed strings
     @param maxLength
     *            maximum length of full string
     */
    public RegexDocument(final String regex, final int maxLength) {
        super(maxLength);
        this.pattern = Pattern.compile(regex);
    }

    @Override
    public void insertString(final int offset, final String str,
                             final AttributeSet attrthrows BadLocationException {
        final Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            super.insertString(offset, str, attr);
        else {
            Toolkit.getDefaultToolkit().beep();
        }
    }


Now this should give you enough info to start delving into documents and working out how you want to use them :)

Enjoy

1 comment:

  1. Thanks for an useful explanation of how to use regex document in a JTextField.

    Angel Arcos

    ReplyDelete