Reputation: 131
I have a textfield in which i have to validate an Email.My problem is that i want to move the focus from the textfield only when the email is valid.I am using now a FocusAdapter. Can someone please give me some other idea?
Upvotes: 0
Views: 2011
Reputation: 11327
See javax.swing.InputVerifier
and JComponent.setInputVerifier()
But don't forget the suggestion from Andrew. Your workflow isn't user friendly.
It was already described here: Java - making a textbox not lose focus
Upvotes: 3
Reputation: 10994
In next example you cant move to another field if validation failed, done with help of requestFocusInWindow()
method. Try it, I think it helps you:
public class Frame extends JFrame {
private JTextField f;
private JTextField f2;
private JTextField f3;
public Frame() {
f = new JTextField(5);
f2 = new JTextField(5);
f3 = new JTextField(5);
f.addFocusListener(getFocusListener());
getContentPane().setLayout(new GridLayout(3,1,5,5));
getContentPane().add(f);
getContentPane().add(f2);
getContentPane().add(f3);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private FocusListener getFocusListener() {
return new FocusAdapter() {
@Override
public void focusLost(FocusEvent arg0) {
super.focusLost(arg0);
if(!validateEmail()){
f.requestFocusInWindow();
}
}
};
}
private boolean validateEmail() {
return f.getText().length()<3;
}
public static void main(String args[]) {
new Frame();
}
}
Read more about requestFocusInWindow() and How to Use the Focus Subsystem
Upvotes: 0
Reputation: 2432
Try this:
public static boolean isValidEmailAddress(String email)
{
boolean result=true;
try
{
InternetAddress emailAddr=new InternetAddress(email);
emailAddr.validate();
} catch(AddressException ex)
{
result=false;
}
return result;
}
Upvotes: 0