Use the same jFormattedTextField for CPF and CNPJ mask

3

I would like to know if it is possible in a same JFormattedTextField , toggle mask for CPF and CNPJ.

When I use the mask of JFormattedTextField the value is already static, and if you put it to the CPF, it will not fit the CNPJ and if it puts in the pattern of the CNPJ, the CPF will be unconfigured.

What I have been trying to do is 2 checkBoxes, each with its own distinction and when selected, apply the correct mask.

Butitisnotcleaningafterselectingamask.ThecodetoinsertthemaskI'musingis:

if(jCheckBox1.isSelected()){try{MaskFormatterformat=newMaskFormatter("##.###.###/####-##");
        format.install(jFormattedTextField1);
    } catch (ParseException ex) {
        Logger.getLogger(FormTeste.class.getName()).log(Level.SEVERE, null, ex);
    }
}
    
asked by anonymous 15.07.2016 / 15:26

1 answer

6

You want to change the field mask at runtime, but install apparently does not work, but according to this response , you need to change it by calling setFormatterFactory() , where needed. In your example, I would suggest moving to JRadioButton to avoid risk of masking conflict.

You create a group, add the radiobuttons in it, so you can only select one item at a time, avoiding the problem mentioned in the previous paragraph.

ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(radioButtonCPF);
radioGroup.add(radioButtonCNPJ);

It is also interesting to create the masks before using them, so that the exception handling of ParseException occurs once only.

private MaskFormatter CNPJMask;
private MaskFormatter CPFMask;

//...

try {
    CNPJMask = new MaskFormatter("##.###.###/####-##");
    CPFMask = new MaskFormatter("###.###.###-##");
} catch (ParseException ex) {
    ex.printStackTrace();
}

Then just add a ItemListener > in every RadioButton , and within intemStateChanged , check if it has been checked:

    radioButtonCPF.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                fmtField.setValue(null);
                fmtField.setFormatterFactory(new DefaultFormatterFactory(CPFMask));
            }
        }
    });

    radioButtonCNPJ.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                fmtField.setValue(null);
                fmtField.setFormatterFactory(new DefaultFormatterFactory(CNPJMask));
            }
        }
    });

The fmtField.setValue(null); must be called before applying the mask, because if you have any content in the field, the exchange is not performed. The consequence of this is that, every time the exchange is effected, what has been typed will be lost.

It can be improved, but the above is already simplified.

Here is an executable example of the masquerade application, should you wish to see it working before changing your code:

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.ParseException;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;

public class ChoiceMaskTextFormattedFieldTest extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private JFormattedTextField fmtField;
    private JRadioButton radioButtonCNPJ;
    private JRadioButton radioButtonCPF;
    private MaskFormatter CNPJMask;
    private MaskFormatter CPFMask;

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new ChoiceMaskTextFormattedFieldTest().setVisible(true);
        });
    }

    public ChoiceMaskTextFormattedFieldTest() {
        initComponents();
    }

    public void initComponents() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(190, 250));
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));

        fmtField = new JFormattedTextField();
        radioButtonCPF = new JRadioButton();

        radioButtonCNPJ = new JRadioButton();

        radioButtonCPF.setText("CPF");
        radioButtonCNPJ.setText("CNPJ");

        // adiciona os radiobuttons no groupbutton
        // pra que apenas um seja selecionavel
        ButtonGroup radioGroup = new ButtonGroup();
        radioGroup.add(radioButtonCPF);
        radioGroup.add(radioButtonCNPJ);

        // cria as mascaras e já a deixa pronta pra uso
        try {
            CNPJMask = new MaskFormatter("##.###.###/####-##");
            CPFMask = new MaskFormatter("###.###.###-##");
        } catch (ParseException ex) {
            ex.printStackTrace();
        }

        // adiciona um listener aos radiobuttons
        radioButtonCPF.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    fmtField.setValue(null);
                    fmtField.setFormatterFactory(new DefaultFormatterFactory(CPFMask));
                }
            }
        });

        radioButtonCNPJ.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    fmtField.setValue(null);
                    fmtField.setFormatterFactory(new DefaultFormatterFactory(CNPJMask));
                }
            }
        });

        contentPane.add(fmtField);
        contentPane.add(Box.createVerticalStrut(30));
        contentPane.add(radioButtonCPF);
        contentPane.add(radioButtonCNPJ);
        contentPane.add(Box.createVerticalStrut(100));
        pack();
    }
}
    
19.07.2016 / 00:22