这是我关于如何限制字符输入长度的代码
class JTextFieldLimit extends PlainDocument {
private int limit;
// optional uppercase conversion
private boolean toUppercase = false;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
toUppercase = upper;
}
@Override
public void insertString
(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) return;
if ((getLength() + str.length()) <= limit) {
if (toUppercase) str = str.toUpperCase();
super.insertString(offset, str, attr);
}
}
}
可以通过txtSample.setDocument(new JTextFieldLimit(30));
这就是我只接受数字的内容(它接受十进制,尽管 w/ci 不需要)
class NumericDocument extends PlainDocument {
protected int decimalPrecision = 0;
protected boolean allowNegative = false;
public NumericDocument(int decimalPrecision, boolean allowNegative) {
super();
this.decimalPrecision = decimalPrecision;
this.allowNegative = allowNegative;
}
@Override
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
if (str != null){
if (StringFormat.isNumeric(str) == false && str.equals(".") == false && str.equals("-") == false){ //First, is it a valid character?
Toolkit.getDefaultToolkit().beep();
return;
}
else if (str.equals(".") == true && super.getText(0, super.getLength()).contains(".") == true){ //Next, can we place a decimal here?
Toolkit.getDefaultToolkit().beep();
return;
}
else if (StringFormat.isNumeric(str) == true && super.getText(0, super.getLength()).indexOf(",") != -1 && offset>super.getText(0, super.getLength()).indexOf(",") && super.getLength()-super.getText(0, super.getLength()).indexOf(".")>decimalPrecision && decimalPrecision > 0){ //Next, do we get past the decimal precision limit?
Toolkit.getDefaultToolkit().beep();
return;
}
else if (str.equals("-") == true && (offset != 0 || allowNegative == false)){ //Next, can we put a negative sign?
Toolkit.getDefaultToolkit().beep();
return;
}
super.insertString(offset, str, attr);
}
return;
}
public static class StringFormat
{
public StringFormat()
{
}
public static boolean isNumeric(String str)
{
try
{
int x = Integer.parseInt(str);
System.out.println(x); return true;
} catch(NumberFormatException nFE)
{
System.out.println("Not an Integer"); return false;
}
}
}
}
以及如何使用此代码:txtSample.setDocument(new NumericDocument(0,false));
现在的问题是txtSample
只能setDocument
一次。如何限制 jtextfield 长度并仅同时接受数字?或者有没有更简单的方法来做到这一点?谢谢。:D