Mega Code Archive

 
Categories / Java Tutorial / Swing
 

Make custom Input Text Formatter for JFormattedTextField

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