限制JFormattedTextField中的字符

时间:2014-11-28 00:41:32

标签: java swing document jformattedtextfield

我试图限制角色' 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;
    }
}
}

非常感谢

2 个答案:

答案 0 :(得分:0)

除了实现自己的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

答案 1 :(得分:0)

最简单的方法是覆盖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个字符 - 如果是,则表示&#34;消耗&#34 34;关键事件(e),以便它不会像平常一样得到处理。

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