I have 2 textfields in a JFrame and I want to validate the data in textfield1 when the focus gets lost from textfield1. So I have used FocusListener
and used showMessageDialog()
in the FocusLost()
method and that then sets back the focus back to textfield1. It works fine when I click on any component inside the JFrame window other than textfield1,but when I click anywhere outside the JFrame window, the showMessageDialog()
gets called two times and the focus goes to textfield2 whereas the focus should remain on textfield1.
@Override
public void focusGained(FocusEvent e) {}
@Override
public void focusLost(FocusEvent e) {
boolean show = false;
String theRegex = "[0-9]";
Pattern checkRegex = Pattern.compile(theRegex);
Matcher regexMatcher = checkRegex.matcher( MemberID );
while ( !regexMatcher.find() && show==false){
JOptionPane.showMessageDialog(null,"Please enter numbers","Validation Error",JOptionPane.ERROR_MESSAGE);
MemberID_Text.requestFocusInWindow();
MemberID_Text.selectAll();
show = true;
}
}