有没有办法防止JFormattedTextField自动清除无效输入?

JDJ*_*JDJ 3 java swing jformattedtextfield

我正在将JFormattedTextField与MaskFormatter应用于它以输入电话号码。

但是,当我输入无效的电话号码(例如“ 123”)然后按一个按钮时,JFormattedTextField会立即删除所有文本。

有没有办法将无效文本保留在那里?

这是一个代码示例:

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(); 

            }

        });
    }
}
Run Code Online (Sandbox Code Playgroud)

如果仅输入一些数字(例如123),然后按按钮,您将看到它如何自动删除所有文本。

好像是因为我指定

maskFormatter.setPlaceholderCharacter('_');
Run Code Online (Sandbox Code Playgroud)

它用下划线替换所有无效字符,尽管我想知道是否有办法既保留无效的123输入,又保留其余的下划线。

JB *_*zet 5

直接从javadoc的第三行开始:

JFormattedTextField允许配置失去焦点时应采取的措施。可能的配置是[...]