Reputation: 23276
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
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
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
Reputation: 13882
Subscribe to keyDown
event on 1st component.
if text length == 3
shift focus to another component. don't forget to undo the effect of current key down
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