Get raw, unformatted, unmasked text from JFormattedTextField

2.1k Views Asked by At

I have a JFormattedTextField that masks a phone number in the format:

 (###) ###-####

I need to retrieve the unformatted, raw ########## to store in a database.

Currently, I am using .getText().replaceAll("\\)", "").replaceAll("\\(", "").replaceAll("-", "").replaceAll(" ", ""), but this just seems like it should be easier.

Is there a way to get the unmasked, unformatted, raw input from a JFormattedTextField?

Here's the MVCE to illustrate:

public static void main(String args[]) {
    final JFormattedTextField phone = new JFormattedTextField();
    try {
        phone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(###) ###-####")));
    } catch(ParseException e) {
        e.printStackTrace();
    }
    phone.setPreferredSize(new Dimension(125, phone.getPreferredSize().height));
    final JButton button = new JButton("Get Text");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println(phone.getText().replaceAll("\\)", "").replaceAll("\\(", "").replaceAll("-", "").replaceAll(" ", ""));
        }
    });
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    panel.add(phone);
    panel.add(button);
    frame.add(panel);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
3

There are 3 best solutions below

2
Maxim Shoustin On

Why do not use MaskFormatter:

    maskF = new MaskFormatter("(###) ###-####");
    maskF.setValueContainsLiteralCharacters ( false );  
    askF.setOverwriteMode ( true );  
    maskF.setValidCharacters ( "0123456789" );  

    fTextField  = new JFormattedTextField(maskF);           
    fTextField.addPropertyChangeListener("value", this);

     //...

    @Override
    public void propertyChange(PropertyChangeEvent e) {
        Object source = e.getSource();
        if (source == fTextField) {

            if(fTextField.getValue() != null){
                System.out.println((fTextField.getValue()));
            } 
        }    
    }

Type (123) 456-7890 and press Enter. The output will be

1234567890

Generally since the mask is not completed , the fTextField.getValue() returns null

full code

public class Main implements PropertyChangeListener {

    private JFormattedTextField fTextField;
    private MaskFormatter maskF ;

      public static void main(String args[]) throws ParseException {              
          new Main().init(); 
      }

    private void init() throws ParseException {
           JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container content = f.getContentPane();
            content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));


            maskF = new MaskFormatter("(###) ###-####");
            maskF.setValueContainsLiteralCharacters ( false );  
            maskF.setOverwriteMode ( true );  
            maskF.setValidCharacters ( "0123456789" );  

            fTextField  = new JFormattedTextField(maskF);           
            fTextField.addPropertyChangeListener("value", this);
            content.add(fTextField );
            f.setSize(300, 100);
            f.setVisible(true);        
    }


    @Override
    public void propertyChange(PropertyChangeEvent e) {
        Object source = e.getSource();
        if (source == fTextField) {

            if(fTextField.getValue() != null){
                System.out.println((fTextField.getValue()));
            } 
        }    
    }
    }
0
Paul Samsotha On

You can use a character class to clean up the code "[\\s()-]"

System.out.println(phone.getText().replaceAll("[\\s()-]", ""));
0
Hana Ziquel On

Create auxiliary variables to put the original value, and store the value in the auxiliary variable to database. JFormattedTextField just to display the changed value of the format.