这是我的代码,我有两个文本字段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

最佳答案

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

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

希望这些说明能帮助您修复代码。您必须了解您不需要自己调用verify(),当字段失去焦点时,swing框架会自动调用它。

07-26 09:14