JTextField stops using MaskFormatter after being cleared

前端 未结 1 1821
情话喂你
情话喂你 2020-12-22 05:57

I\'m doing a Sudoku solver and for that I want my JTextFields to only accept one of the numbers 123456789 as valid input. Therefore I use a MaskFormatter toghether with a JF

相关标签:
1条回答
  • 2020-12-22 06:39

    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.

    0 讨论(0)
提交回复
热议问题