如果你想让textfield只能输入数字.那可以用我下面帖出的代码.
/*
* OnlyNumberTextField.java
*
* Created on 2007年8月30日, 下午5:57
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package com.test;
import javax.swing.text.BadLocationException;
import javax.swing.text.AttributeSet;
import javax.swing.text.PlainDocument;
import javax.swing.text.Document;
import javax.swing.JTextField;
/**
*
* @author Administrator
*/
public class OnlyNumberTextField extends JTextField {
public OnlyNumberTextField() {
super();
}
public OnlyNumberTextField(int cols) {
super(cols);
}
protected Document createDefaultModel() {
return new NumberDocument();
}
static class NumberDocument extends PlainDocument {
public void insertString(int offset,String str,AttributeSet a)
throws BadLocationException {
if(str==null) return;
char[] chars=str.toCharArray();
int length=0;
for(int i=0;i<chars.length;i++){
if(chars[i]>='0'&&chars[i]<='9')
chars[length++]=chars[i];
}
super.insertString(offset,new String(chars,0,length),a);
}
}
}