javaswingjtextfieldinputverifier

JTextField InputVerifier


I set input verifier to my text field:

public class MyInputVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
    String text = ((JTextField) input).getText();
    try {
        BigDecimal value = new BigDecimal(text);
        return (value.scale() <= Math.abs(4));
    } catch (NumberFormatException nfe) {
        return false;
    }
}

public static class Tester extends JFrame implements ActionListener {
    JTextField tf1;
    JButton okBtn;

    public Tester() {
        add(panel(), BorderLayout.CENTER);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 500);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Tester();
            }
        });
    }

    public JPanel panel() {
        JPanel panel = new JPanel();
        okBtn = new JButton("Ok");
        okBtn.addActionListener(this);
        tf1 = new JTextField(10);
        tf1.setInputVerifier(new MyInputVerifier());
        panel.add(tf1);
        panel.add(okBtn);
        return panel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        MyInputVerifier inputVerifier = new MyInputVerifier();
        if (e.getSource() == okBtn) {
            if (inputVerifier.verify(tf1)) JOptionPane.showMessageDialog(null, "True");
            else JOptionPane.showMessageDialog(null,"False");
        }
    }
}
}

I enter 55555 on text field, and it show true, Why?


Solution

  • From the javadoc

    If zero or positive, the scale is the number of digits to the right of the decimal point.

    55555 can be represented without scaling so its scale is zero -> 0 < 4 which is true

    I suspect you want to compare against the numeric value

    return (value.compareTo(BigDecimal.valueOf(4)) <= 0);