// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;

import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.JFormattedTextField.AbstractFormatterFactory;

public class Formatting2 extends JFrame {
    private JFormattedTextField jftf;
    private JButton jbtn;
    public Formatting2() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new BorderLayout());
        setTitle("Formatting");
        jftf = new JFormattedTextField();
        jftf.setFormatterFactory(new AbstractFormatterFactory() {
            @Override
            public AbstractFormatter getFormatter(JFormattedTextField tf) {
                return new AbstractFormatter() {
                    @Override
                    public Object stringToValue(String text) throws ParseException {
                        if(text.equals("")) return null;
                        return new Foobar2(Integer.parseInt(text.substring(4, text.length()-4)));
                    }
                    @Override
                    public String valueToString(Object value) throws ParseException {
                        if(value == null) return "";
                        if(value instanceof Foobar2) {
                            return "****" + ((Foobar2)value).getV() + "****";
                        } else {
                            throw new RuntimeException(value.getClass().getName() + " is not supported");
                        }
                    }
                };
            }
        
        });
        jftf.setValue(new Foobar2(177));
        getContentPane().add(jftf, BorderLayout.CENTER);
        jbtn = new JButton("Test");
        jbtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ((Foobar2)jftf.getValue()).test();
            }
        });
        getContentPane().add(jbtn, BorderLayout.SOUTH);
        pack();
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new Formatting2();
                f.setVisible(true);
            }
        });
    }
}

class Foobar2 {
    private int v;
    public Foobar2(int v) {
        this.v = v;
    }
    public int getV() {
        return v;
    }
    public void setV(int v) {
        this.v = v;
    }
    @Override
    public String toString() {
        return Integer.toString(v);
    }
    public void test() {
        JOptionPane.showMessageDialog(null, "v=" + v);
    }
}
