<2025年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          統計

          • 隨筆 - 0
          • 文章 - 22
          • 評論 - 11
          • 引用 - 0

          留言簿

          文章分類(22)

          文章檔案(21)

          牛B天地

          搜索

          •  

          最新評論

          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)  編輯  收藏 所屬分類: 程序設計

          主站蜘蛛池模板: 纳雍县| 铜川市| 海伦市| 富锦市| 巴彦淖尔市| 宁津县| 大港区| 孟津县| 左云县| 元谋县| 通城县| 新乐市| 利川市| 中宁县| 富裕县| 慈溪市| 东明县| 苍梧县| 鲁甸县| 桃园县| 邳州市| 萍乡市| 黎川县| 义乌市| 肥西县| 和林格尔县| 宜章县| 砀山县| 广德县| 法库县| 工布江达县| 仁化县| 饶阳县| 汉源县| 江阴市| 岑巩县| 卢氏县| 聂荣县| 乌拉特后旗| 揭东县| 奇台县|