Numeric (Number only) JTextField in Swing: Ready made code

  

Here’s a ready made Numeric(Numbers only) text field written as a swing component. This text field allows only numeric data to be entered in it. When the user enters anything that non numeric in the text field, the system will beep. It’s implemented using a DocumentFilter that filters out all non-numeric characters from being entered in the Swing textfield’s document

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;
 
public class NumericTextField extends JTextField {	 
  //Add other constructors as required. If you do,
  //be sure to call the "addFilter" method
  public NumericTextField(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 NumericDocumentFilter());
  }
 
 
  class NumericDocumentFilter extends DocumentFilter{
    public void insertString(FilterBypass fb, 
      int offset, String string, AttributeSet attr) 
        throws BadLocationException {
 
      if(string == null) return;
      if(isStringNumeric(string)){
        super.insertString(fb, offset, string, attr);
      }
      else{
        Toolkit.getDefaultToolkit().beep();
      }
    }
 
    public void replace(FilterBypass fb, int offset, 
      int length, String text, AttributeSet attrs) 
        throws BadLocationException {
      if(text == null) return;
      if(isStringNumeric(text)){
        super.replace(fb, offset, length, text, attrs);
      }
      else{
        Toolkit.getDefaultToolkit().beep();
      }
    }
 
    private boolean isStringNumeric(String string){
     char[] characters = string.toCharArray();
     for(char c: characters){
       if(! Character.isDigit(c)){					 
         return false;
       }
     }
     return true;
    }
  }
}






2 Responses to 'Numeric (Number only) JTextField in Swing: Ready made code'

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

    […] An “Numeric” text-field: That accepts only numeric input and ignores all others […]

  2. Jul's - December 11th, 2008 at 4:11 am

    How to use it..??? Please help me


Leave a Reply





Popular Articles

Blog Categories

Monthly Archives

Resources