import javax.swing.text.*;
import java.awt.*;
/**
* 描述:使用格式JTextField.setDocument(new NumberDocument())即可
**/
public class NumberDocument extends PlainDocument {
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
char[] source = str.toCharArray();
char[] result = new char[source.length];
int j = 0;
for (int i = 0; i < result.length; i++){
if( Character.isDigit(source[i]) ) //是數字
result[j++] = source[i];
else{ //不是數字
Toolkit.getDefaultToolkit().beep();
System.out.println("你輸入了非數字字符!!")
}
}
super.insertString(offs,new String(result,0,j),a);
}
}
沒有留言:
張貼留言