Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8927677
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T08:16:18+00:00 2026-06-15T08:16:18+00:00

Is there a way to get a list of components within a JPanel according

  • 0

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();
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T08:16:19+00:00Added an answer on June 15, 2026 at 8:16 am

    Take a look at Container#getFocusTraversalPolicy, which returns a FocusTraversalPolicy which 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) and FocusTraversalPolicy#getComponentAfter(Container, Component)

    If that doesn’t work, you may need to write your self a custom Comparator and sort the array of components accordingly

    UPDATED – Focus Traversal Example

    public class ComponentOrder {
    
        public static void main(String[] args) {
            new ComponentOrder();
        }
    
        public ComponentOrder() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    BodyPane body = new BodyPane();
    
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(body);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    
                    Container focusRoot = body.getFocusCycleRootAncestor();
                    FocusTraversalPolicy ftp = focusRoot.getFocusTraversalPolicy();
                    Component comp = ftp.getFirstComponent(body);
                    Component first = comp;
                    while (comp != null) {
                        System.out.println(" - " + comp);
                        comp = ftp.getComponentAfter(focusRoot, comp);
                        if (comp.equals(first)) {
                            break;
                        }
                    }
                }
            });
        }
    
        public class BodyPane extends JPanel {
    
            private JTextField fldFirstName;
            private JTextField fldMiddleName;
            private JTextField fldLastName;
            private JTextField fldDateOfBirth;
            private JTextField fldEMail;
            private JButton okButton;
            private JButton cancelButton;
    
            public BodyPane() {
    
                setLayout(new BorderLayout());
                add(createFieldsPane());
                add(createButtonsPane(), BorderLayout.SOUTH);
    
            }
    
            public JPanel createButtonsPane() {
    
                JPanel panel = new JPanel(new FlowLayout());
                panel.add((okButton = createButton("Ok")));
                panel.add((cancelButton = createButton("Cancel")));
    
                return panel;
    
            }
    
            protected JButton createButton(String text) {
    
                return new JButton(text);
    
            }
    
            public JPanel createFieldsPane() {
    
                JPanel panel = new JPanel(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.insets = new Insets(2, 2, 2, 2);
                gbc.gridx = 0;
                gbc.gridy = 0;
                gbc.anchor = GridBagConstraints.WEST;
    
                panel.add(createLabel("First Name:"), gbc);
                gbc.gridy++;
                panel.add(createLabel("Middle Name:"), gbc);
                gbc.gridy++;
                panel.add(createLabel("Last Name:"), gbc);
                gbc.gridy++;
                panel.add(createLabel("Date of Birth:"), gbc);
                gbc.gridy++;
                panel.add(createLabel("EMail:"), gbc);
    
                gbc.gridy = 0;
                gbc.gridx++;
                gbc.weightx = 1;
                panel.add((fldFirstName = createField()), gbc);
                gbc.gridy++;
                panel.add((fldLastName = createField()), gbc);
                gbc.gridy++;
                panel.add((fldMiddleName = createField()), gbc);
                gbc.gridy++;
                panel.add((fldDateOfBirth = createField()), gbc);
                gbc.gridy++;
                panel.add((fldEMail = createField()), gbc);
    
                JPanel filler = new JPanel();
                filler.setOpaque(false);
    
                gbc.gridy++;
                gbc.weightx = 1;
                gbc.weighty = 1;
                panel.add(filler, gbc);
    
                return panel;
    
            }
    
            protected JLabel createLabel(String text) {
    
                return new JLabel(text);
    
            }
    
            protected JTextField createField() {
    
                JTextField field = new JTextField(12);
                return field;
    
            }
        }
    }
    

    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.LayoutComparator which is package protected (which was nice of the SwingTeam) and modified it to convert the component coordinates back into the parent coordinate space

    public class ComponentOrder {
    
        public static void main(String[] args) {
            new ComponentOrder();
        }
    
        public ComponentOrder() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    BodyPane body = new BodyPane();
    
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(body);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    
                    List<Component> components = new ArrayList<Component>(25);
                    getContents(body, components);
                    LayoutComparator lc = new LayoutComparator(body);
                    lc.setComponentOrientation(body.getComponentOrientation());
                    Collections.sort(components, lc);
                    for (Component comp : components) {
                        System.out.println(comp);
                    }
                }
            });
        }
    
        protected void getContents(Container container, List<Component> components) {
            for (Component comp : container.getComponents()) {
                components.add(comp);
                if (comp instanceof Container) {
                    getContents((Container) comp, components);
                }
            }
        }
    
        public class BodyPane extends JPanel {
    
            private JTextField fldFirstName;
            private JTextField fldMiddleName;
            private JTextField fldLastName;
            private JTextField fldDateOfBirth;
            private JTextField fldEMail;
            private JButton okButton;
            private JButton cancelButton;
    
            public BodyPane() {
                setLayout(new BorderLayout());
                add(createFieldsPane());
                add(createButtonsPane(), BorderLayout.SOUTH);
            }
    
            public JPanel createButtonsPane() {
                JPanel panel = new JPanel(new FlowLayout());
                panel.add((okButton = createButton("Ok")));
                panel.add((cancelButton = createButton("Cancel")));
                return panel;
            }
    
            protected JButton createButton(String text) {
                return new JButton(text);
            }
    
            public JPanel createFieldsPane() {
                JPanel panel = new JPanel(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.insets = new Insets(2, 2, 2, 2);
                gbc.gridx = 0;
                gbc.gridy = 0;
                gbc.anchor = GridBagConstraints.WEST;
    
                panel.add(createLabel("First Name:"), gbc);
                gbc.gridy++;
                panel.add(createLabel("Middle Name:"), gbc);
                gbc.gridy++;
                panel.add(createLabel("Last Name:"), gbc);
                gbc.gridy++;
                panel.add(createLabel("Date of Birth:"), gbc);
                gbc.gridy++;
                panel.add(createLabel("EMail:"), gbc);
    
                gbc.gridy = 0;
                gbc.gridx++;
                gbc.weightx = 1;
                panel.add((fldFirstName = createField("FirstName")), gbc);
                gbc.gridy++;
                panel.add((fldLastName = createField("LastName")), gbc);
                gbc.gridy++;
                panel.add((fldMiddleName = createField("MiddleName")), gbc);
                gbc.gridy++;
                panel.add((fldDateOfBirth = createField("DateOfBirth")), gbc);
                gbc.gridy++;
                panel.add((fldEMail = createField("EMail")), gbc);
    
                JPanel filler = new JPanel();
                filler.setOpaque(false);
    
                gbc.gridy++;
                gbc.weightx = 1;
                gbc.weighty = 1;
                panel.add(filler, gbc);
    
                return panel;
            }
    
            protected JLabel createLabel(String text) {
                JLabel label = new JLabel(text);
                label.setName(text);
                return label;
            }
    
            protected JTextField createField(String name) {
                JTextField field = new JTextField(12);
                field.setName("Field-" + name);
                return field;
            }
        }
    
        public class LayoutComparator implements Comparator<Component>, java.io.Serializable {
    
            private static final int ROW_TOLERANCE = 10;
            private boolean horizontal = true;
            private boolean leftToRight = true;
    
            private Component parent;
    
            public LayoutComparator(Component parent) {
                this.parent = parent;
            }
    
            void setComponentOrientation(ComponentOrientation orientation) {
                horizontal = orientation.isHorizontal();
                leftToRight = orientation.isLeftToRight();
            }
    
            public int compare(Component a, Component b) {
                if (a == b) {
                    return 0;
                }
    
                // Row/Column algorithm only applies to siblings. If 'a' and 'b'
                // aren't siblings, then we need to find their most inferior
                // ancestors which share a parent. Compute the ancestory lists for
                // each Component and then search from the Window down until the
                // hierarchy branches.
                if (a.getParent() != b.getParent()) {
                    LinkedList<Component> aAncestory = new LinkedList<Component>();
    
                    for (; a != null; a = a.getParent()) {
                        aAncestory.add(a);
                        if (a instanceof Window) {
                            break;
                        }
                    }
                    if (a == null) {
                        // 'a' is not part of a Window hierarchy. Can't cope.
                        throw new ClassCastException();
                    }
    
                    LinkedList<Component> bAncestory = new LinkedList<Component>();
    
                    for (; b != null; b = b.getParent()) {
                        bAncestory.add(b);
                        if (b instanceof Window) {
                            break;
                        }
                    }
                    if (b == null) {
                        // 'b' is not part of a Window hierarchy. Can't cope.
                        throw new ClassCastException();
                    }
    
                    for (ListIterator<Component> aIter = aAncestory.listIterator(aAncestory.size()),
                                    bIter = bAncestory.listIterator(bAncestory.size());;) {
                        if (aIter.hasPrevious()) {
                            a = aIter.previous();
                        } else {
                            // a is an ancestor of b
                            return -1;
                        }
    
                        if (bIter.hasPrevious()) {
                            b = bIter.previous();
                        } else {
                            // b is an ancestor of a
                            return 1;
                        }
    
                        if (a != b) {
                            break;
                        }
                    }
                }
    
                Point pa = SwingUtilities.convertPoint(a, a.getLocation(), parent);
                Point pb = SwingUtilities.convertPoint(b, b.getLocation(), parent);
    
                int ax = pa.x, ay = pa.y, bx = pb.x, by = pb.y;
    
                int zOrder = a.getParent().getComponentZOrder(a) - b.getParent().getComponentZOrder(b);
                if (horizontal) {
                    if (leftToRight) {
    
                        // LT - Western Europe (optional for Japanese, Chinese, Korean)
    
                        if (Math.abs(ay - by) < ROW_TOLERANCE) {
                            return (ax < bx) ? -1 : ((ax > bx) ? 1 : zOrder);
                        } else {
                            return (ay < by) ? -1 : 1;
                        }
                    } else { // !leftToRight
    
                        // RT - Middle East (Arabic, Hebrew)
    
                        if (Math.abs(ay - by) < ROW_TOLERANCE) {
                            return (ax > bx) ? -1 : ((ax < bx) ? 1 : zOrder);
                        } else {
                            return (ay < by) ? -1 : 1;
                        }
                    }
                } else { // !horizontal
                    if (leftToRight) {
    
                        // TL - Mongolian
    
                        if (Math.abs(ax - bx) < ROW_TOLERANCE) {
                            return (ay < by) ? -1 : ((ay > by) ? 1 : zOrder);
                        } else {
                            return (ax < bx) ? -1 : 1;
                        }
                    } else { // !leftToRight
    
                        // TR - Japanese, Chinese, Korean
    
                        if (Math.abs(ax - bx) < ROW_TOLERANCE) {
                            return (ay < by) ? -1 : ((ay > by) ? 1 : zOrder);
                        } else {
                            return (ax > bx) ? -1 : 1;
                        }
                    }
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Given that: There seems to be no easy way to get a list of
Is there a way to get a list of all open sockets ( socket
Is there a way to get the list of currently running threads in objective-C?
Is there a way to get the list index name in my lapply() function?
Is there some way to get a distinct list of file extensions on all
I was wondering if there is a way to get a list of results
Is there a way to get all versions of list item(s) using a CAML
Is there a quick way to get a flattened List<TElement> from an ILookup<TKey, TElement>
Is there a way to get the previous item in a list , based
Is there a way using SWT to get a list of all processes currently

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.