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.  * upper case 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 UpperCaseField extends JTextField {  
  19.        
  20.     /** 
  21.      *  
  22.      */  
  23.     private static final long serialVersionUID = 6854878572763032459L;  
  24.   
  25.     public UpperCaseField(int cols) {  
  26.         // super() 可以被自动调用,但是有参构造方法并不能被自动调用,只能依赖   
  27.         // super关键字显示地调用父类的构造方法   
  28.         super(cols);  
  29.     }  
  30.   
  31.     protected Document createDefaultModel() {  
  32.         return new UpperCaseDocument();  
  33.     }  
  34.   
  35.     static class UpperCaseDocument extends PlainDocument {  
  36.   
  37.         /** 
  38.          *  
  39.          */  
  40.         private static final long serialVersionUID = -4170536906715361215L;  
  41.   
  42.         public void insertString(int offs, String str, AttributeSet a)  
  43.             throws BadLocationException {  
  44.   
  45.             if (str == null) {  
  46.                 return;  
  47.             }  
  48.             char[] upper = str.toCharArray();  
  49.             for (int i = 0; i < upper.length; i++) {  
  50.                 upper[i] = Character.toUpperCase(upper[i]);  
  51.             }  
  52.             super.insertString(offs, new String(upper), a);  
  53.         }  
  54.     }  
  55. }  

相关内容