简体   繁体   中英

How to get components of a JPanel which inside another JPanel in java

I have a JPanel(first JPanel) and it fill with another JPanel(second JPanel).

I add this second JPanel to first JPanel programmatically. Like below,

firstJPanel.removeAll();
JPanel secondJPanel = new JPanel(gridLayout);
secondJPanel.setBorder(new TitledBorder("Testing"));
secondJPanel.setName("secondJPanel");
firstJPanel.add(secondJPanel);
firstJPanel.revalidate();

The second JPanel has some components like JTextFields , JCheckBoxes, etc . I try to get these components . But I could get only the second JPanel.

Here is my code sample,

Component[] components = firstJPanel.getComponents();
for(int i=0;i<components.length;i++){
     System.out.println("Componenet name - " + components[i].getName());           
}

Have any iedas to get the components inside the second JPanel.

Best Regards.

You can use like

Component[] components = firstJPanel.getComponents();
for (int i = 0; i < components.length; i++) {
    System.out.println("Componenet name - " + components[i].getName());
    if (components[i] instanceof JPanel
            && components[i].equals(secondJPanel)) {

        Component s[] = ((JPanel) components[i]).getComponents();
        for (int j = 0; j < s.length; j++) {
            System.out.println("Sub Componenet name - " + s[j].getName());
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM