Java only supports text boxes with uppercase letters

Source: Internet
Author: User

[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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.