How does Swing determine which component to give focus to when Tab is pressed?
How does Swing determine which component to change focus to when Tab is pressed? Does it have to do with the order i开发者_JS百科n which the components are declared? Created? Added? Their absolute positions on the screen? Or is there no reliable pattern at all?
The AWT (or Swing) FocusManager uses a FocusTraversalPolicy to determine which component gets the focus next.
I think the default FocusTraversalPolicy is look-and-feel dependent, but where I observed it, it was either a ContainerOrderFocusTraversalPolicy (which simply sorts the components by their index in the parent) or a LayoutFocusTraversalPolicy.
This last mentioned class does some ordering on the components of the container by their position, roughly fitting them in lines and traversing them line by line, and in the lines from left to right (or right to left on RTL-locales). This works best when using some grid-based layout manager like GridLayout, GridBagLayout, GroupLayout and such.
Ah, I retract my comment. From Hovercraft's link (emphasis mine):
A focus traversal policy determines the order in which a group of components are navigated. Swing provides the LayoutFocusTraversalPolicy class, which decides the order of navigation based on layout manager-dependent factors, such as size, location, and orientation of components. Within a focus cycle, components can be navigated in a forward or backward direction.
I must have missed that when I was reading last night.
Hovercraft, if you post an answer like this one, I'll delete this and accept yours.
精彩评论