JTextField上的输入验证程序返回错误

时间:2013-10-04 09:04:03

标签: java swing jtextfield inputverifier

这是我的代码,我有两个文本字段tf1tf2

public class MyInputVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
    String name = input.getName();
    if (name.equals("tf1")) {
        System.out.println("in tf1");
        String text = ((JTextField) input).getText().trim();
        if (text.matches(".*\\d.*")) return false;       // have digit
    }
    else if (name.equals("tf2")) {
        System.out.println("in tf2");
        String text = ((JTextField) input).getText().trim();
        if (isNumeric2(text)) return true;
    }
    return false;
}

public boolean isNumeric2(String str) {
    try {
        Integer.parseInt(str);
        return true;
    } catch (Exception e) {
        return false;
    }
}

public static class Tester extends JFrame implements ActionListener {
    JTextField tf1, tf2;
    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(new FlowLayout(FlowLayout.LEFT));
        okBtn = new JButton("Ok");
        okBtn.addActionListener(this);
        tf1 = new JTextField(10);
        tf1.setName("tf1");
        tf2 = new JTextField(10);
        tf2.setName("tf2");
        tf1.setInputVerifier(new MyInputVerifier());
        tf2.setInputVerifier(new MyInputVerifier());
        panel.add(tf1);
//            panel.add(tf2);
        panel.add(okBtn);
        return panel;
    }

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

输出:

我输入10

on joption pane: false in tf2
on console: in tf1
            in tf2

1 个答案:

答案 0 :(得分:3)

根据doc,当verify()松散焦点时调用JTextField方法。在您的代码中,单击okbtn时tf1松散焦点。因此,调用tf1的verify()方法并打印in tf1

在actionPerformed中,您明确调用verify()方法,以便打印in tf2。由于tf2为空(即您在JPanel中添加它的行已注释):JOptionPane显示false in tf2

我希望这些解释可以帮助您修复代码。您必须了解自己不需要自己调用verify(),当字段松散焦点时,swing框架会自动调用它。