Is there a way to get a list of components within a JPanel according to the order that they display in the JPanel (Top left to bottom right), and not the order that they were added to the JPanel?
This seems to get the components in the order that they were added to the panel
Component[] comps = myJPanel.getComponents();
Take a look at
Container#getFocusTraversalPolicy, which returns aFocusTraversalPolicywhich has methods to determine the focus movement through a container.This (should) provide you with the natural order of the components (from the perspective of the layout manager and focus manager)
I’d start with
FocusTraversalPolicy#getFirstComponent(Container)andFocusTraversalPolicy#getComponentAfter(Container, Component)If that doesn’t work, you may need to write your self a custom
Comparatorand sort the array of components accordinglyUPDATED – Focus Traversal Example
Comparator example
The following example uses a comparator to determine the flow of the components. This version translates all the components from a parent container into that containers coordinate space, so it should be possible to use this with compound containers.
nb I stole the comparator from
javax.swing.LayoutComparatorwhich is package protected (which was nice of the SwingTeam) and modified it to convert the component coordinates back into the parent coordinate space