Create custom formatter for JFormattedTextField in Java

Description

The following code shows how to create custom formatter for JFormattedTextField.

Example


import java.awt.BorderLayout;
import java.text.ParseException;
/*w ww. j a v  a2  s  .  c  om*/
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 ParseException {
    JFrame frame = new JFrame("Formatted Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JFormattedTextField tf = new JFormattedTextField(new MyFormatter());
    tf.setColumns(10);

    frame.add(tf, 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";
    }
  }
}

The code above generates the following result.

Create custom formatter for JFormattedTextField in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer