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