重载 replaceSelection()。
给个例子,您自己看一下吧。import javax.swing.*;/**仅接受数字键入*/
public class NumericField extends JTextField{
  private String tempLocS;  public void replaceSelection(String content) {
    tempLocS = "";
    char c;
    for (int i = 0; i < content.length(); i++){
      c = content.charAt(i);
      if (! (c >'9' || c<'0'))
        tempLocS += c;
    }
    super.replaceSelection(tempLocS);
  }
}
/**不接受非法文件名字符*/
class fileNameTextField extends JTextField{
  private String tempLocS, invalidChar = ":*?\"<>|";  public void replaceSelection(String content) {
    tempLocS = "";
    char c;
    for (int i = 0; i < content.length(); i++){
      c = content.charAt(i);
      if (invalidChar.indexOf(c)<0)
        tempLocS += c;
    }
    super.replaceSelection(tempLocS);
  }
}