Java Swing DefaultFormatter extend to create custom formatter

Description

Java Swing DefaultFormatter extend to create custom formatter

import java.awt.BorderLayout;
import java.text.ParseException;

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

public class Main {
   public static void main(final String args[]) throws Exception {
      JFrame frame = new JFrame("Formatted Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      JFormattedTextField input = new JFormattedTextField(new MyFormatter());
      input.setColumns(10);//from w ww.  j ava  2  s .  c om

      frame.add(input, BorderLayout.NORTH);

      frame.add(new JTextField(), BorderLayout.SOUTH);
      frame.setSize(250, 100);
      frame.setVisible(true);
   }
}

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";
      }
   }
}



PreviousNext

Related