【问题标题】:Limit characters in a JFormattedTextField限制 JFormattedTextField 中的字符
【发布时间】:2016-02-15 00:02:41
【问题描述】:

我正在尝试限制 JFormattedTextField 中的字符数。我正在使用正则表达式来验证字段,但我也需要限制输入。

我尝试了 DocumentFilter 和 PlainDocument,但没有成功。这是我的代码:

public class UsingRegexFormatter {

public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JFormattedTextField formattedField = new JFormattedTextField(new RegexFormatter("[0-9]+([,\\.][0-9]+)*"));
    //trying to limit to 3 characters with no success...
    formattedField.setDocument(new JTextFieldLimit(3));
    frame.add(formattedField, "North");

    frame.add(new JTextField(), "South");

    frame.setSize(300, 200);
    frame.setVisible(true);
}

static class JTextFieldLimit extends PlainDocument {

    private int limit;

    public JTextFieldLimit(int limit) {
        super();
        this.limit = limit;
    }

    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if (str == null) {
            return;
        }

        if ((getLength() + str.length()) <= limit) {
            super.insertString(offset, str, attr);
        }
    }
}

static class RegexFormatter extends DefaultFormatter {

    private Pattern pattern;

    private Matcher matcher;

    public RegexFormatter() {
        super();
    }

    /**
     * Creates a regular expression based AbstractFormatter. pattern
     * specifies the regular expression that will be used to determine if a
     * value is legal.
     */
    public RegexFormatter(String pattern) throws PatternSyntaxException {
        this();
        setPattern(Pattern.compile(pattern));
    }

    /**
     * Creates a regular expression based AbstractFormatter. pattern
     * specifies the regular expression that will be used to determine if a
     * value is legal.
     */
    public RegexFormatter(Pattern pattern) {
        this();
        setPattern(pattern);
    }

    /**
     * Sets the pattern that will be used to determine if a value is legal.
     */
    public void setPattern(Pattern pattern) {
        this.pattern = pattern;
    }

    /**
     * Returns the Pattern used to determine if a value is legal.
     */
    public Pattern getPattern() {
        return pattern;
    }

    /**
     * Sets the Matcher used in the most recent test if a value is legal.
     */
    protected void setMatcher(Matcher matcher) {
        this.matcher = matcher;
    }

    /**
     * Returns the Matcher from the most test.
     */
    protected Matcher getMatcher() {
        return matcher;
    }

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

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

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

非常感谢

【问题讨论】:

  • PlainDocument 不是DocumentFilter
  • JFormattedTextField 是那些安装它自己的过滤器或Document 以促进其功能的烦人类之一,但只有在它添加到 UI 之后才会这样做......:P跨度>
  • 我的意思是我尝试了 DocumentFilter 和 PlainDocument,但它仍然不起作用..
  • 我似乎记得外观和感觉安装了它自己的Document 或其他东西,但有些东西弄乱了它......:P
  • 好的,当专注时,JFormattedTextField 会安装它自己的DocumentFilter...这是一个完全的痛苦。 JFormattedTextField 真的不做实时过滤,当字段失去焦点或被操作时它是验证...

标签: java swing document jformattedtextfield


【解决方案1】:

除了实现您自己的 JFormattedTextField 类之外,一种可能的解决方法是使用 maskformatter,然后只使用 * 作为分隔符以允许任何字符

MaskFormatter formatter = new MaskFormatter("************"); //with however many characters you need

formatter.setValidCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");`// whatever characters you would use

JFormattedTextField textField = new JFormattedTextField(formatter); 

原帖:http://www.javalobby.org/java/forums/t48584.html

【讨论】:

  • 然后可以使用常规文本字段并以这种方式限制字符。您应该能够使用实现正则表达式验证类的自定义类来验证信息。除非您尝试动态执行此操作。以下是我在研究此事时遇到的一些链接:stackoverflow.com/questions/15269507/…stackoverflow.com/questions/3537093/…
  • 好吧,我通过重写 RegexFormatter 中的 getDocumentFilter() 方法来获得我自己的 documentFilter,谢谢 :)
【解决方案2】:

最简单的方法是覆盖 keyTyped() 事件以在一定限制后丢弃字符。下面是我在课程中使用的 GuessingGame 的一个简单示例:

txtGuess = new JTextField();
txtGuess.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) { 
        if (txtGuess.getText().length() >= 3 ) // limit textfield to 3 characters
            e.consume(); 
    }  
});

这会将猜谜游戏文本字段中的字符数限制为 3 个字符,方法是覆盖 keyTyped 事件并检查文本字段是否已经有 3 个字符 - 如果是,您正在“消耗”键事件(e ) 这样它就不会像平常一样被处理。

希望它有所帮助 - 只是一种不同的方法。干杯!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 2014-09-23
    • 2013-08-07
    • 2010-09-11
    • 2022-11-17
    • 2012-11-09
    • 1970-01-01
    相关资源
    最近更新 更多