Link to home
Start Free TrialLog in
Avatar of vi_sharma
vi_sharma

asked on

How to move the cursor back to a text field ?

I am using Java Swing .I have a dialog box in which there are three JTextFields. A user can enter some data in a text field and I validate that data before user moves to the next field by pressing "TAB" or using mouse to point to the next field. I have registered focusListener on these three JTextFields and as the focus is lost from one field, i call my method x() to validate the data entered by user. If the data is wrong, a message window is displayed showing to the user what was wrong in the data entered. Now my problem is I call method x() in focusLost(e) method and even if there is an error message, the cursor moves to the next field which I don't want. I want the cursor to be placed back to the textfield whose validation generated the error so that the user can correct it and if it is correct, then only cursor should move to the next textfield. Immediate help will be appreciated.
Avatar of refactor
refactor

Use requestFocus() method?
Avatar of vi_sharma

ASKER

Can you explain in detail how to use it? I tried it..but it's not working..
You can also listen to focusGet events and when the textfield that should get focus gets the focus execute "previousTextField.requestFocus()" which would give the focus to the "previousTextField" text field.

 You can use SwingUtilities.invokeLater method for requestFocus call.


public void focusLost( FocusEvent e ){

   // blah blah blah .....

  if( error ){
  SwingUtilities.invokeLater( new Runnable(){
     public void run(){
           textField1.requestFocus();
     }

});
  }
}

 This will solve your problem...

Sankar S.
ASKER CERTIFIED SOLUTION
Avatar of anand29
anand29

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial