简体   繁体   English

使用正则表达式格式化程序的JFormattedTextField?

[英]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? 在让JFormattedTextField与我的自定义格式一起使用后,我感到非常沮丧,我想知道是否有使用正则表达式的FormatterFormatterFactory

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 " 我想使用JFormattedTextField来允许用户将持续时间值输入到表单中。示例有效值为: 2h 30m 72h 15m 6h 0h

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: 如果链接腐烂,它表示你真正需要做的就是覆盖AbstractFormatter的stringToValue方法,如下所示:

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? 哪些都不足以满足您的需求?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM