數據加載中……
          JAVA:JTextField文本框輸入過濾
           1 import javax.swing.text.AttributeSet;
           2 import javax.swing.text.BadLocationException;
           3 import javax.swing.text.PlainDocument;
           4 
           5 public class LimitedDocument extends PlainDocument {
           6 
           7     private int maxLength = -1;
           8     private String allowCharAsString = null;
           9 
          10     public LimitedDocument() {
          11         super();
          12     }
          13 
          14     public LimitedDocument(int maxLength, String str) {
          15         super();
          16         this.maxLength = maxLength;
          17         allowCharAsString = str;
          18     }
          19 
          20     @Override
          21     public void insertString(int offset, String str, AttributeSet attrSet)
          22             throws BadLocationException {
          23 
          24         if (str == null) {
          25             return;
          26         }
          27 
          28         if (allowCharAsString != null && str.length() == 1) {
          29             if (allowCharAsString.indexOf(str) == -1) {
          30                 return;
          31             }
          32         }
          33 
          34         char[] charVal = str.toCharArray();
          35         String strOldValue = getText(0, getLength());
          36         byte[] tmp = strOldValue.getBytes();
          37 
          38         if (maxLength != -1 && (tmp.length + charVal.length > maxLength)) {
          39             return;
          40         }
          41 
          42         super.insertString(offset, str, attrSet);
          43     }
          44 }

                 用法:
          1 LimitedDocument Input = new LimitedDocument(maxLength,allowCharAsString);
          2 maxLength 為最大輸入長度,allowCharAsString 為允許輸入的字符
          3 jTextField.setDocument(Input); 運用到文本框中

                 例如:
          1 String AllowChar = "0123456789";
          2 LimitedDocument Input = new LimitedDocument(11,AllowChar)


          posted on 2009-05-25 10:32 YeeYang 閱讀(915) 評論(0)  編輯  收藏 所屬分類: 程序設計

          主站蜘蛛池模板: 克什克腾旗| 东至县| 长宁县| 赤城县| 山丹县| 乐至县| 荆门市| 伊宁县| 交城县| 宝丰县| 汶川县| 嘉义市| 沈丘县| 泸西县| 寻甸| 大兴区| 玉门市| 纳雍县| 西峡县| 安宁市| 习水县| 监利县| 历史| 邢台市| 荆门市| 四子王旗| 吴江市| 馆陶县| 博罗县| 葫芦岛市| 呈贡县| 兴国县| 玛纳斯县| 泸水县| 中阳县| 固始县| 吴川市| 基隆市| 涡阳县| 乐东| 邯郸县|