Java中限制文本框的输入

4

有没有一种方法可以限制文本字段只允许输入0-100的数字,从而排除字母、符号等? 我找到了一种方法,但它似乎比必要的复杂。


你具体是在谈论哪个类?java.awt.TextField吗? - Michael Krauklis
1
很高兴知道你找到的方法... - user85421
4个回答

10

如果您必须使用文本字段,应该使用带有NumberFormatterJFormattedTextField。您可以在NumberFormatter上设置允许的最小和最大值。

NumberFormatter nf = new NumberFormatter();
nf.setValueClass(Integer.class);
nf.setMinimum(new Integer(0));
nf.setMaximum(new Integer(100));

JFormattedTextField field = new JFormattedTextField(nf);

然而,如果适用于您的使用情况,Johannes建议使用JSpinner也是合适的。


哦,这个不错。我还不知道呢。+1 因为这实际上是一个文本字段而不是一个带滚动条的文本字段 :-) - Joey
JFormattedTextField 也可以很好地与 InputVerifier 结合使用:http://java.sun.com/javase/6/docs/api/javax/swing/InputVerifier.html - trashgod

5

我建议你在这种情况下使用JSpinner。在Swing中,即使是最基本的单行文本框也有一个完整的Document类,因此与之一起工作相当复杂。


1

您可以设置一个DocumentFilter,用于JTextField使用的PlainDocument。在更改Document的内容之前,将调用DocumentFilter的方法,并且可以补充或忽略这些更改:

    PlainDocument doc = new PlainDocument();
    doc.setDocumentFilter(new DocumentFilter() {
        @Override
        public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr)
        throws BadLocationException {
            if (check(fb, offset, 0, text)) {
                fb.insertString(offset, text, attr);
            }
        }
        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
        throws BadLocationException {
            if (check(fb, offset, length, text)) {
                fb.replace(offset, length, text, attrs);
            }
        }
        // returns true for valid update
        private boolean check(FilterBypass fb, int offset, int i, String text) {
            // TODO this is just an example, should test if resulting string is valid
            return text.matches("[0-9]*");
        }
    });

    JTextField field = new JTextField();
    field.setDocument(doc);

在上面的代码中,您必须完成check方法以满足您的要求,最终获取字段的文本并替换/插入文本以检查结果。

0

你必须实现并添加一个新的DocumentListener到你的textField.getDocument()。我在这里找到了一个实现here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接