Sometimes present formatters are inappropriate to use. In that condition you can define your own custom Input Text Formatter.

This sample code shows the way of defining custom text formatter. It makes a text formatter 'MyFormatter' which will allow the integer of range 1 to 1000. If the input in the text field is not in this range then the text box will show invalid.

 import java.text.ParseException;
import javax.swing.text.DefaultFormatter;
public class MyFormatter extends DefaultFormatter {
    public MyFormatter() {
    // This method reads the text from model class to view class
    public String valueToString(Object arg0) throws ParseException {
        return super.valueToString(arg0);
    // This method reads the text from view class to modal class and does the validations
    public Object stringToValue(String arg0) throws ParseException {
        try {
            int value=Integer.parseInt(arg0);
                return ""+value;
                return "Invalid";
        } catch (Exception e) {
            return "Invalid";

The following class uses the MyFormatter.
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MyFormatterExp extends JFrame{
    public MyFormatterExp() {
        setTitle("Example: Custom Formatter");
        JPanel panel = new JPanel();
        JLabel label = new JLabel("Number :");
        JFormattedTextField tf=new JFormattedTextField(new MyFormatter());
        JButton button = new JButton();
        button.setLabel("Click kMe");
        getContentPane().add(panel, BorderLayout.SOUTH);
    public static void main(String[] args) {
        MyFormatterExp mfe = new MyFormatterExp();