JTextField stops using MaskFormatter after being cleared

纵饮孤独 提交于 2019-11-29 17:31:28

I can't tell you the exact reason but setText seems to drive your JFormattedTextField crazy because "" is a String and it is against the current mask.

Please try using setValue(null) instead.

I've just made sure that this method works. The next piece of code proves it:

public class Two extends JFrame {

    public static void main(String[] args) throws Exception {
        new Two().a();
    }

    void a() throws Exception {
        this.setLayout(new GridLayout(2, 1));
        MaskFormatter formatter = new MaskFormatter("#");
        formatter.setValidCharacters("123456789");
        final JFormattedTextField field = new JFormattedTextField(formatter);
        JButton b = new JButton("null!");
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                field.setValue(null);
            }
        });
        this.add(field);
        this.add(b);
        this.setSize(100, 100);
        this.setVisible(true);
    }
}

After clicking the null! button formatter continues to work as it is supposed to work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!