我正在使用 LostFocus 事件验证两个文本字段,如下所示:
textRegNo.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent arg0) {
// TODO Auto-generated method stub
regNo1=textRegNo.getText();
Pattern pattern1 = Pattern.compile("^[A-Z]{2}[ -][0-9]{1,2}(?: [A-Z])?(?: [A-Z]*)? [0-9]{4}$");
Matcher matcher1 = pattern1.matcher(regNo1);
if (!matcher1.find()){
JOptionPane.showMessageDialog(null, "Invalid Vehicle No!!!\n Vehicle no should be of the form MH 03 KS 2131!!");
}
}
@Override
public void focusGained(FocusEvent arg0) {
// TODO Auto-generated method stub
};
});
textMobNo.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent arg0) {
// TODO Auto-generated method stub
mobNo1=textMobNo.getText();
Pattern pattern2 = Pattern.compile("^[789]\\d{9}$");
Matcher matcher2 = pattern2.matcher(mobNo1);
System.out.println("'"+mobNo1+"'");
if (!matcher2.find()){
JOptionPane.showMessageDialog(null, "Phone no must be a 10 digit number!!");
}
}
@Override
public void focusGained(FocusEvent arg0) {
// TODO Auto-generated method stub
};
});
我的问题是,当我失去对第一个文本字段的关注并将焦点移动到第二个文本字段时,两个字段都会打印错误消息(两个 lostfocus 事件下的 IF 块内的消息。)当我在第一个文本字段中输入错误并移动焦点时对于第二个字段,它应该只打印第一个文本字段的错误消息。但两者的打印错误。
第一个文本字段是 textRegNo 第二个文本字段是 textMobNo