java - 有没有办法防止 JFormattedTextField 自动删除无效输入?

标签 java swing jformattedtextfield

我正在使用应用了 MaskFormatter 的 JFormattedTextField 来输入电话号码。

但是,当我输入无效的电话号码(例如“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(); 

            }

        });
    }
}

如果您只输入几个数字,例如 123,然后按下按钮,您将看到它如何自动删除所有文本。

好像是因为我指定了

maskFormatter.setPlaceholderCharacter('_');

它正在用下​​划线替换所有无效字符,尽管我想知道是否有办法保留无效的 123 输入以及剩余的下划线。

最佳答案

直接从 the javadoc 的第三行开始:

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

关于java - 有没有办法防止 JFormattedTextField 自动删除无效输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20966601/

相关文章:

java - 在 Java 中通过 JFormattedTextFields 进行验证

java - 安卓java |更新 View 布局参数时出现卡顿和滞后

java - 尝试显示向下移动的圆圈,但无法删除之前绘制的圆圈

java - 将 JFormattedTextField 中的多个值分配给多个变量

java - textPanel.setText ("");不工作或不显示

java - 如何在 SWT/Swing 中收集频繁的更新/重绘/布局/刷新操作?

java - 如何将表单字段放入列表中以便能够迭代它们?

java - 模拟模拟 pageContext 的 httpRequest

java - 如何将字符串转换为多项式并对其进行加减?

java - Hibernate Envers 将数据恢复为一个版本