MyFormatter.java Source code

Java tutorial

Introduction

Here is the source code for MyFormatter.java

Source

import java.text.ParseException;

import javax.swing.JFormattedTextField;
import javax.swing.text.DefaultFormatter;

class MyFormatter extends DefaultFormatter {

    public MyFormatter() {
        super();
    }

    public String valueToString(Object object) throws ParseException {
        return super.valueToString(object);
    }

    public Object stringToValue(String string) throws ParseException {
        try {
            int value = Integer.parseInt(string);
            if (value != 1) {
                return "" + value;
            } else {
                return "Invalid";
            }
        } catch (Exception e) {
            return "Invalid";
        }
    }
}

public class Main {

    public static void main(String[] args) {
        JFormattedTextField tf = new JFormattedTextField(new MyFormatter());
        tf.setColumns(10);
    }
}