自己实现一个 DocumentFilter 示例代码如下import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class DocSizeFilter extends JFrame {
    public static final int MAX_SIZE = 16;
    private JTextField jtf;    public DocSizeFilter() {
        AbstractDocument aDoc;        jtf = new JTextField();
        aDoc = (AbstractDocument) jtf.getDocument();
        aDoc.setDocumentFilter(new SizeFilter(MAX_SIZE));
        getContentPane().add(jtf);
    }    public static void main(String[] args) {
        DocSizeFilter frame = new DocSizeFilter();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }    private class SizeFilter extends DocumentFilter {
        int maxSize;
        int size;
        Pattern p = Pattern.compile("[0-9]");
        Matcher m = p.matcher("");        public SizeFilter(int maxSize) {
            this.maxSize = maxSize;
        }        public void insertString(FilterBypass fb, int offset, String string,
                                 AttributeSet attr) throws BadLocationException {
            size = fb.getDocument().getLength() + string.length();
            m.reset(string);
            if (size < maxSize && m.matches()) {
                super.insertString(fb, offset, string, attr);
            }
        }        public void replace(DocumentFilter.FilterBypass fb, int offset,
                            int length,String text, AttributeSet attrs)
                throws BadLocationException {
            size = fb.getDocument().getLength() + text.length();
            m.reset(text);
            if (size < maxSize && m.matches()) {
                super.insertString(fb, offset, text, attrs);
            }
        }
    }
}

解决方案 »

  1.   

    这个是只能输入整数的TextField,编译好了,直接用就行,我已经使用好多次了  :)/** 
     *@author:   WangXitao     Date:2004/4/25
     *@function: Create a TextField PlainDocument,which is allowed input Integer
     */import javax.swing.*; 
    import javax.swing.text.*; 
    import java.awt.*; 
    import java.awt.event.*; public class WxtIntegerTextField extends JTextField{
           private WxtIntegerDocument plainDoc=null;
           public WxtIntegerTextField(){
                  super();
                  setDocument(plainDoc=new WxtIntegerDocument(this));
                  setHorizontalAlignment(JTextField.RIGHT);
           }
    }class WxtIntegerDocument extends PlainDocument{
           private JTextComponent myComponent=null;
           public WxtIntegerDocument(JTextComponent txtComponent){
                  myComponent=txtComponent;
           }
           
           public void insertString(int offset, String s,AttributeSet attributeSet) throws BadLocationException{
                  if (s != null) {
                        StringBuffer buffer = new StringBuffer(s);
                        for (int i = buffer.length() - 1; i >= 0; i--) {
                              char ch = buffer.charAt(i);
                              if (!Character.isDigit(ch) && ch != ',' )
                                     buffer.deleteCharAt(i);
                       }
                       s = buffer.toString();
                  }
          super.insertString(offset, s, attributeSet); 
           }
           
           public void replace(int offset, int length, String s, AttributeSet attributeSet) throws BadLocationException {
                  String  Value  =  myComponent.getText();
                  String  str    = "";
                  String  Result = "";
                  if(myComponent.getText().length()>0){
                          str = myComponent.getText().substring(0,1);
    if(s.equals("-")){
    if(offset==0 && !(str.equals("-"))){
    Result = s + Value;
    }else{
            Toolkit.getDefaultToolkit().beep();  //Transfer the System's ring
    return;
    }
    }else{
    Result = Value.substring(0,offset) + s + Value.substring(offset);
    }
    }else{
    if(s.equals("-")){
    //super.insertString(offset, s, attributeSet);
    Toolkit.getDefaultToolkit().beep();  //Transfer the System's ring
    return;
    }else{
    Result = s;
    }
    } try { 
    long value = Long.parseLong(Result); 
    if(value>999999 || value<=0) {
    Toolkit.getDefaultToolkit().beep();  //Transfer the System's ring 
    return; 
    }
    /**if(value>Integer.MAX_VALUE || value<Integer.MIN_VALUE) { 
    return; 
    }*/ 

    catch(Exception ex) {
    Toolkit.getDefaultToolkit().beep();  //Transfer the System's ring
    return; 

              super.replace(offset, length, s, attributeSet); 
          }}
      

  2.   

    这个是只能输入日期的TextField,日期格式:04-08-02,我也用了好多次了. :)
    请参考/** 
     *@author:   WangXitao     Date:2004/4/25
     *@function: Create a TextField,which is allowed input 0--9 and '-'
     */import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;public class WxtDateTextField extends JTextField{
           private WxtDatePlainDocument plainDoc=null;
           public WxtDateTextField(int maxLen){
                  super();
                  setDocument(plainDoc=new WxtDatePlainDocument(maxLen));
                  setHorizontalAlignment(JTextField.RIGHT);
           }
           public WxtDateTextField(){
                  super();
                  setDocument(plainDoc=new WxtDatePlainDocument());
                  setHorizontalAlignment(JTextField.RIGHT);
           }
           
           public void setMaxLength(int max){
                  plainDoc.setMaxLength(max);
           }
           
           public int getMaxLength(){
                  return plainDoc.getMaxLength();
           } 
    }
                          
    class WxtDatePlainDocument extends PlainDocument{
           private int maxLength=100; //The default max length of TextField
           
           public WxtDatePlainDocument(int MaxLen){
                  this.maxLength=MaxLen;
           }
           
           public WxtDatePlainDocument(){}
           
           public void setMaxLength(int max){
                  this.maxLength=max;
           }
           
           public int getMaxLength(){
                  return this.maxLength;
           }
           
           public void insertString(int offset,String s,AttributeSet a) throws BadLocationException{
                    int len=getLength();
    String str=getText(0,len);

    if ( (str+s).length()>maxLength ){
    Toolkit.getDefaultToolkit().beep();  //Transfer the System's ring
    return;
    }

    try{
    java.util.StringTokenizer tokens = new java.util.StringTokenizer( str+s,"-" );
    while( tokens.hasMoreElements() ) {
    Integer.parseInt( (String)tokens.nextElement() );  //If parameter is not a number,
    }                                                          //it will throw an Exception 
    }catch ( Exception e ){
    Toolkit.getDefaultToolkit().beep();
            return;
    }

    super.insertString(offset,s,a);
    }
    }
      

  3.   

    textfield.getDocument().addDocumentListener()