1

I'm trying to use MaskFormatter with JFormattedTextField.

Inside my class I have this line of code

JFormattedTextField jtfCNP=new JFormattedTextField(new MaskFormatter(formatCNP));

When I compile, I get the ParseException. The only way around it I found to create the instance of the MaskFormatter inside the constructor of my GUI panel inside a try block like this

    try { format_cnp=new MaskFormatter("# ###### ######");
    jtf_cnp=new JFormattedTextField(format_cnp);
    } catch (ParseException pex) {}
    jtf_cnp.setColumns(20);

I'd like the functionality of the MaskFormatter, but isn't there any way to instantiate it outside a method? Also, is there a better alternative to MaskFormatter?

Edit: the sample code that doesn't work:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import javax.swing.text.*;

    public class test extends JFrame{

        String formatCNP="# ###### ######";
        //components
        JFormattedTextField jtfCNP=new JFormattedTextField(new MaskFormatter(formatCNP));

        public test(){

        super("MaskFormatter Test");
        setSize(300,300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        jtfCNP.setColumns(20);
        add(jtfCNP);

        setVisible(true);

        }

        public static void main(String[] args){

            test tf=new test();
        }

    }
4

1 に答える 1