Java只允许输入数字的文本框


Java只允许输入数字的文本框:

  1. package com.han;  
  2.   
  3. import javax.swing.JTextField;  
  4. import javax.swing.text.AttributeSet;  
  5. import javax.swing.text.BadLocationException;  
  6. import javax.swing.text.Document;  
  7. import javax.swing.text.PlainDocument;  
  8.   
  9. /** 
  10.  * Customized fields can easily be created by extending the model  
  11.  * and changing the default model provided. For example,  
  12.  * the following piece of code will create a field that holds only  
  13.  * digit characters. It will work even if text is pasted into from  
  14.  * the clipboard or it is altered via programmatic changes. 
  15.  * @author HAN 
  16.  * 
  17.  */  
  18. public class DigitOnlyField extends JTextField {  
  19.        
  20.     
  21.   
  22.     /** 
  23.      *  
  24.      */  
  25.     private static final long serialVersionUID = 8384787369612949227L;  
  26.   
  27.     public DigitOnlyField(int cols) {  
  28.         // super() 可以被自动调用,但是有参构造方法并不能被自动调用,只能依赖   
  29.         // super关键字显示地调用父类的构造方法   
  30.         super(cols);  
  31.     }  
  32.   
  33.     protected Document createDefaultModel() {  
  34.         return new UpperCaseDocument();  
  35.     }  
  36.   
  37.     static class UpperCaseDocument extends PlainDocument {  
  38.   
  39.         /** 
  40.          *  
  41.          */  
  42.         private static final long serialVersionUID = -4170536906715361215L;  
  43.   
  44.         public void insertString(int offs, String str, AttributeSet a)  
  45.             throws BadLocationException {  
  46.   
  47.             if (str == null) {  
  48.                 return;  
  49.             }  
  50.             char[] upper = str.toCharArray();  
  51.             String filtered = "";  
  52.             for (int i = 0; i < upper.length; i++) {  
  53.                 if (Character.isDigit(Character.codePointAt(upper, i))){  
  54.                     filtered += upper[i];  
  55.                 }  
  56.             }  
  57.             super.insertString(offs, filtered, a);  
  58.         }  
  59.     }  
  60. }  

相关内容