【发布时间】:2010-01-26 13:14:04
【问题描述】:
有没有办法限制文本字段只允许数字 0-100,从而排除字母、符号等?我找到了一种方法,但它比看起来需要的复杂得多。
【问题讨论】:
-
你具体说的是什么课? java.awt.TextField?
-
很高兴知道您找到的方式...
有没有办法限制文本字段只允许数字 0-100,从而排除字母、符号等?我找到了一种方法,但它比看起来需要的复杂得多。
【问题讨论】:
如果您必须使用文本字段,则应使用 JFormattedTextField 和 NumberFormatter。您可以设置 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 也是合适的。
【讨论】:
JFormattedTextField 也适用于InputVerifier :java.sun.com/javase/6/docs/api/javax/swing/InputVerifier.html
在这种情况下,我建议您使用JSpinner。在 Swing 中使用文本字段非常复杂,因为即使是最基本的单行字段也有一个成熟的 Document 类。
【讨论】:
您可以设置JTextField 使用的PlainDocument 的DocumentFilter。 DocumentFilter 的方法会在Document 的内容改变之前被调用,可以补充或忽略这个改变:
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方法来匹配你的要求,最终得到字段的文本并替换/插入文本来检查结果。
【讨论】:
您必须实现并添加一个新的DocumentListener 到您的 textField.getDocument()。我找到了一个实现here。
【讨论】: