|
|
Here’s a ready made Upper case text field written as a swing component. It converts all characters entered in it automatically to upper case before inserting into it’s own document. So the when the user types in this text field he will see only characters in upper case irrespective of the case with which he types. There is no limitation to use this code. Use it in whatever way you like. package kaushik.test; import java.awt.Toolkit; import javax.swing.JTextField; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; import javax.swing.text.DocumentFilter.FilterBypass; import kaushik.test.NumericTextField.NumericDocumentFilter; public class UpperCaseTextField extends JTextField{ //Add other constructors as required. If you do, //be sure to call the "addFilter" method public UpperCaseTextField(String text, int columns){ super(text, columns); addFilter(); } //Add an instance of NumericDocumentFilter as a document filter //to the current text field private void addFilter(){ ((AbstractDocument)this.getDocument()). setDocumentFilter(new UppercaseDocumentFilter()); } //This DocumentFilter will modify all characters entered //in the text field to upper case and then submit it to the //document class UppercaseDocumentFilter extends DocumentFilter{ public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { if(string == null) return; string = string.toUpperCase(); super.insertString(fb, offset, string, attr); } public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if(text == null) return; text = text.toUpperCase(); super.replace(fb, offset, length, text, attrs); } } } 2 Responses to 'Upper Case JTextField in Swing: Ready made code'Leave a Reply |
Popular Articles
Blog Categories
Monthly Archives
Resources
|
[…] An “upper case” text-field: That automatically converts the characters to upper case as the user types in […]
I want to ask how to use it..Please teach me..Thanks a lot..