Upper Case JTextField in Swing: Ready made code

  

    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'

  1. Ready made Simple Custom TextField components » Java Swing - July 27th, 2008 at 8:17 am

    […] An “upper case” text-field: That automatically converts the characters to upper case as the user types in […]

  2. handoyo - September 27th, 2008 at 7:58 am

    I want to ask how to use it..Please teach me..Thanks a lot..


Leave a Reply





Popular Articles

Blog Categories

Monthly Archives

Resources