Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFormattedTextField using a regular expression formatter?

After much frustration with getting a JFormattedTextField to work with my custom formats, I was wondering if there was a Formatter or FormatterFactory that uses regular expressions?

My idea is that if there is one, then I could wrap it in a static class and invoke it like so:

mFormattedTextField.setFormatterFactory(
    SomeStaticClass.getRegexFormatFactory("^(\\d{1,}h)(\\s([0-5])?[0-9]m)?$"));

See my previous question for more background:
" I want to use a JFormattedTextField to allow the user to input time duration values into a form. Sample valid values are: 2h 30m 72h 15m 6h 0h"

like image 206
bguiz Avatar asked Feb 11 '10 02:02

bguiz


People also ask

How to Use formatted text fields Java?

You can specify the formatters to be used by a formatted text field in several ways: Use the JFormattedTextField constructor that takes a Format argument. A formatter for the field is automatically created that uses the specified format. Use the JFormattedTextField constructor that takes a JFormattedTextField.

Which method of JTextField returns the selected text contained by the text field?

Notice the use of JTextField 's getText method to retrieve the text currently contained by the text field. The text returned by this method does not include a newline character for the Enter key that fired the action event.


1 Answers

Have you read this article? In case that link rots away, it says all you really need to do override AbstractFormatter's stringToValue method, like this:

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

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

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

Actually, a quick search yields several fully-implemented, free solutions; were none of those sufficient to your needs?

like image 194
Alan Moore Avatar answered Oct 06 '22 06:10

Alan Moore