Frage

I am using a JFormattedTextField with a MaskFormatter applied to it in order to input a phone number.

However, when I enter an invalid phone number, such as "123" and then press a button, the JFormattedTextField immediately erases all of the text.

Is there a way to keep that invalid text in there?

Here is a code example:

import java.awt.FlowLayout;
import java.text.ParseException;

import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.text.MaskFormatter;

public class Example extends JFrame 
{
    private JFormattedTextField formattedTextField;

    public Example() 
    {
        this.getContentPane().setLayout(new FlowLayout());

        try
        {
            MaskFormatter maskFormatter = new MaskFormatter("(###) ###-####");
            maskFormatter.setPlaceholderCharacter('_');
            formattedTextField = new JFormattedTextField(maskFormatter);
        }
        catch (ParseException pe)
        {
            System.out.println("Parse Exception");
        }

        JButton button = new JButton("OK");

        add(formattedTextField);
        add(button);
    }

    private static void createAndShowGUI() 
    {
        JFrame frame = new Example();

        frame.pack();

        frame.setLocationRelativeTo(null);

        frame.setVisible(true);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) 
    {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            public void run() {

                createAndShowGUI(); 

            }

        });
    }
}

If you enter only a few digits, such as 123, and then press the button, you will see how it automatically deletes all of the text.

It seems as though because I specify

maskFormatter.setPlaceholderCharacter('_');

it is replacing all of the invalid characters with the underscore, although I would like to know if there were a way to retain both the invalid 123 input, and also the remaining underscores.

War es hilfreich?

Lösung

Straight from the third line of the javadoc:

JFormattedTextField allows configuring what action should be taken when focus is lost. The possible configurations are [...]

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top