[Java]
Package com. han;
Import javax. swing. JTextField;
Import javax. swing. text. AttributeSet;
Import javax. swing. text. BadLocationException;
Import javax. swing. text. Document;
Import javax. swing. text. PlainDocument;
/**
* Customized fields can easily be created by extending the model
* And changing the default model provided. For example,
* The following piece of code will create a field that holds only
* Upper case characters. It will work even if text is pasted into from
* The clipboard or it is altered via programmatic changes.
* @ Author HAN
*
*/
Public class UpperCaseField extends JTextField {
/**
*
*/
Private static final long serialVersionUID = 6854878572763032459L;
Public UpperCaseField (int cols ){
// Super () can be called automatically, but the construction method with parameters cannot be called automatically.
// The super keyword is displayed to call the constructor of the parent class.
Super (cols );
}
Protected Document createDefaultModel (){
Return new UpperCaseDocument ();
}
Static class UpperCaseDocument extends PlainDocument {
/**
*
*/
Private static final long serialVersionUID =-127051096715361215l;
Public void insertString (int offs, String str, AttributeSet)
Throws BadLocationException {
If (str = null ){
Return; www.2cto.com
}
Char [] upper = str. toCharArray ();
For (int I = 0; I <upper. length; I ++ ){
Upper [I] = Character. toUpperCase (upper [I]);
}
Super. insertString (offs, new String (upper), );
}
}
}
Author: Gaowen_HAN