有没有一种方法可以限制文本字段只允许输入0-100的数字,从而排除字母、符号等? 我找到了一种方法,但它似乎比必要的复杂。
如果您必须使用文本字段,应该使用带有NumberFormatter 的JFormattedTextField。您可以在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
结合使用:http://java.sun.com/javase/6/docs/api/javax/swing/InputVerifier.html - trashgod您可以设置一个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
方法以满足您的要求,最终获取字段的文本并替换/插入文本以检查结果。