0

这是我的代码,我有两个文本字段,tf1并且tf2

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
4

1 回答 1

3

根据文档,当焦点松动verify()时调用该方法。JTextField在您的代码中,tf1单击 okbtn 时放松焦点。所以verify()调用 tf1 的方法并打印in tf1

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

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

于 2013-10-04T09:45:20.750 回答