【问题标题】:Is there a way to prevent a JFormattedTextField from automatically erasing invalid input?有没有办法防止 JFormattedTextField 自动擦除无效输入?
【发布时间】:2014-01-24 20:07:53
【问题描述】:

我正在使用一个带有 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 输入以及剩余的下划线。

【问题讨论】:

  • 是的输入掩码有4个选项,

标签: java swing jformattedtextfield


【解决方案1】:

直接从the javadoc的第三行:

JFormattedTextField 允许配置当焦点丢失时应该采取什么行动。可能的配置是 [...]

【讨论】:

  • formattedTextField.setFocusLostBehavior(JFormattedTextField.COMMIT) 似乎有效。
猜你喜欢
  • 2011-09-24
  • 1970-01-01
  • 2011-10-24
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
相关资源
最近更新 更多