[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
* Digit characters. It will work even if text is pasted into from
* The clipboard or it is altered via programmatic changes.
* @ Author HAN
*
*/
Public class DigitOnlyField extends JTextField {
/**
*
*/
Private static final long serialVersionUID = 8384787425612942527l;
Public DigitOnlyField (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 );
} Www.2cto.com
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;
}
Char [] upper = str. toCharArray ();
String filtered = "";
For (int I = 0; I <upper. length; I ++ ){
If (Character. isDigit (Character. codePointAt (upper, I ))){
Filtered + = upper [I];
}
}
Super. insertString (offs, filtered, );
}
}
}
Author: Gaowen_HAN