【发布时间】:2016-10-14 08:07:56
【问题描述】:
对于一个小测试应用程序,我需要一个只接受数字的 TextField。此外,用户应该只能输入 0-255 之间的数字。到目前为止,我发现了这个:
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
/**
* A JTextField that accepts only integers.
*
* @author David Buzatto
*/
public class IntegerField extends JTextField {
public IntegerField() {
super();
}
public IntegerField( int cols ) {
super( cols );
}
@Override
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
static class UpperCaseDocument extends PlainDocument {
@Override
public void insertString( int offs, String str, AttributeSet a )
throws BadLocationException {
if ( str == null ) {
return;
}
char[] chars = str.toCharArray();
boolean ok = true;
for ( int i = 0; i < chars.length; i++ ) {
try {
Integer.parseInt( String.valueOf( chars[i] ) );
} catch ( NumberFormatException exc ) {
ok = false;
break;
}
}
if ( ok ) {
super.insertString( offs, new String( chars ), a );
}
}
}
我在 for 循环中添加了以下内容,因此只能输入包含 3 位数字的数字
if(super.getLength() == 3) {
ok = false;
System.out.println("tooLong");
break;
}
但是如何设置最大输入值?用户只能输入 0-255 之间的数字。
提前致谢
【问题讨论】:
-
输入>= 0 && 输入
-
我知道,但是我应该如何实现这个我从哪里获得/如何获得输入? super.length() 很简单,但我如何制作 super.getInput super.getText?
标签: java swing validation document