1

我将输入验证器设置为我的文本字段:

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");
        }
    }
}
}

55555在文本字段中输入,它显示true,为什么?

4

1 回答 1

6

来自javadoc

如果为零或正数,则刻度是小数点右侧的位数。

55555可以在没有缩放的情况下表示,因此它的比例为零 ->0 < 4这是true

我怀疑您想与数值进行比较

return (value.compareTo(BigDecimal.valueOf(4)) <= 0);
于 2013-09-25T19:19:19.500 回答