Currency mask for JTextField

2

I have a JTextField field that should receive a monetary value from the user. I would like to add a mask to this field so that it will format the values entered as follows: 9999.99.

    
asked by anonymous 19.11.2014 / 19:26

1 answer

5

The easiest way, @Rodox, is to use the MaskFormatter class.

First you create an instance of class MaskFormatter with a constructor in this format:

MaskFormatter mascaraCampo = null;
try {
    mascaraCampo= new MaskFormatter("#.###,##");
}catch (ParseException e) {
}

After that, you just have to instantiate JFormattedTextField , passing the mask as a parameter.

JFormattedTextField campoFormatado = new JFormattedTextField(mascaraCampo);

Functional example:

public class Funcional {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setBounds(0, 0, 310, 330);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);         
        MaskFormatter mascaraCampo = null;
        try {
            mascaraCampo = new MaskFormatter("#.###,##");
        } catch (ParseException e) {
        }
        JFormattedTextField campoFormatado = new JFormattedTextField(mascaraCampo);
        campoFormatado.setVisible(true);
        campoFormatado.setBounds(25, 25, 245, 30);
        frame.add(campoFormatado);
        frame.setVisible(true);
    }

}
    
21.11.2014 / 12:35