Suhail Gupta
Suhail Gupta

Reputation: 23276

Shifting focus from one component to another

How can I shift focus from one component to another component when I (program) experience's' a certain case ? Like the focus shifts to the next text-field when in the first text field the word length reaches 3.

Upvotes: 0

Views: 900

Answers (3)

pavannpg
pavannpg

Reputation: 41

This works well..

 Component currentFocusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
                            FocusEvent focusLostEvent = new FocusEvent(currentFocusOwner, 1005, true, destinationComponent);
                            FocusEvent focusGainEvent = new FocusEvent(destinationComponent, 1004, true, currentFocusOwner);                        
                            try
                            {
                                currentFocusOwner.dispatchEvent(focusLostEvent);
                                destinationComponent.dispatchEvent(focusGainEvent);
                            }
                            catch(Exception e)
                            {
                                Logger.logExceptionMessage(e);
                            }

Upvotes: 0

program-o-steve
program-o-steve

Reputation: 2678

You can do like this :

if(jTextField1.getText().length() == 2 ){ // if the req. length is 3
        // shift the focus to next text field
        jTextField2.requestFocusInWindow();
    }

Upvotes: 0

Azodious
Azodious

Reputation: 13882

  1. Subscribe to keyDown event on 1st component.

  2. if text length == 3 shift focus to another component. don't forget to undo the effect of current key down

  3. I guess focus() OR requestFocusInWindow() method can be used. don't remember exact name.

Similarly, TextChanged event can be subscribed. so, ASA 3 chars are added, shift the focus using step 3.

Upvotes: 1

Related Questions