jtextfield限制字數與數字輸入

import javax.swing.text.*;

public class NumberLenghtLimitedDmt extends PlainDocument {
 
   private int limit;
   public NumberLenghtLimitedDmt(int limit) {
    super();
       this.limit = limit;
    } 
   public void insertString
     (int offset, String  str, AttributeSet attr)
                                   throws BadLocationException {  
       if (str == null){
        return;
       }
       if ((getLength() + str.length()) <= limit) {
      
       char[] upper = str.toCharArray();
       int length=0;
       for (int i = 0; i < upper.length; i++) {      
           if (upper[i]>='0'&&upper[i]<='9'){          
              upper[length++] = upper[i];
           }
       }
         super.insertString(offset, new String(upper,0,length), attr);
      }
    }
}

用法:

JTextField  text=new JTextField();

text.setDocument(new NumberLenghtLimitedDmt(7));

那麼這個文本框只能輸入7位而且是隻能是數字!!!
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章