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?
Asked
Active
Viewed 1,934 times
0
-
4I'd hate to have to work with a program that behaves that way. E.G. I'm sitting in front of a screen with 30 fields, and know the values of 29 of them, but the 30th is the email address that I need to get from my co-worker who has popped outside for a smoke. Why limit me from entering the details of the 29 fields I know? *"..give me some other idea?"* Validate all the fields when the operator ***attempts to save the information.*** If there are fields that need fixing, pop a modal dialog explaining the data needed & drop them back into the form, with field focused. – Andrew Thompson Nov 14 '13 at 11:16
3 Answers
3
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

Community
- 1
- 1

Sergiy Medvynskyy
- 11,160
- 1
- 32
- 48
0
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;
}

KernelPanic
- 2,328
- 7
- 47
- 90
-
I have validated the Email.My problem is: when i type in some not valid email in the TextField and i move the mouse on another Component ,I need the mouse not to be able to do that,but to stay on the same Textfield until the email is valid. – Laura Nov 14 '13 at 11:22
0
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

alex2410
- 10,904
- 3
- 25
- 41