限制JFormattedTextField中的字符 [英] Limit characters in a JFormattedTextField

查看:154
本文介绍了限制JFormattedTextField中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to restrict the characters' number in a JFormattedTextField. I'm using a regular expression to validate the field but I need to limit the input too.

我尝试了DocumentFilter和PlainDocument,但是没有用.这是我的代码:

I tried DocumentFilter and PlainDocument but it didn't work. Here is my code:

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;
    }
}
}

非常感谢您

推荐答案

最简单的方法是重写keyTyped()事件以在特定限制后丢弃字符.这是我在课程中使用的GuessingGame的简单示例:

Easiest way is to override the keyTyped() event to throw away characters after a certain limit. Here's a simple example from a GuessingGame I use in my courses:

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

通过覆盖keyTyped事件并检查文本字段是否已经包含3个字符,这将猜测游戏文本字段中的字符数限制为3个字符-如果是这样,则说明您正在消费"键事件(例如),这样就不会像平常一样得到处理.

This limits the number of characters in a guessing game text field to 3 characters, by overriding the keyTyped event and checking to see if the textfield already has 3 characters - if so, you're "consuming" the key event (e) so that it doesn't get processed like normal.

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

Hope it helps a bit - just a different approach. Cheers!

这篇关于限制JFormattedTextField中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆