Question

I've an Swing GUI application that has JTabbedPane and multiple panels in it. It has about 9 Jpanels, in the 1st JPanel i ve four JPanels and these Jpanels contains some swing components. I've set these Panels names.

My Question is : I am able to read these components in the first tab panel but the problem is not able to get the Name of the panel and proceed further.

Code is as follows:

1., Sample class:

import java.awt.Component;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;

public class Sample {

    public Sample() {}

    public List<Component> getComponents(int id , Object obj) {
        List<Component> result = new ArrayList<Component>();
        if (id == 1 && obj instanceof ExampleTab1) {
            Component[] component =((ExampleTab1)obj).getContentPanel().getComponents();
            for (Component comp : component) {
                if (comp instanceof JPanel) {                                              
                    String compName = ((JPanel)comp).getName().toString();
                    if (compName.equals("panelResult")) {
                        //do the stuff
                    }
                }
            }
        }
        return result;
    }
}

2., ExampleTab1 class:

import javax.swing.JPanel;

public class ExampleTab1 {
    public ExampleTab1() { }
    public JPanel getContentPanel()  {
        JPanel contentPane = new JPanel();
        //all the components added to the panel 
        return contentPane;
    }
}
Was it helpful?

Solution

If you want to have all elements from a Container (like JPanel or JTabbedPane, etc...) you need to collect them manually, because the getComponents() is only reading the direct children of the Container.

You need to add the following function to the Sample class:

public List<Component> getAllComponents(Container container) {
    Component[] components = container.getComponents();
    List <Component> result = new ArrayList<Component>();
    for (Component component : components) {
        result.add(component);
        if (component instanceof Container) {
            result.addAll(getAllComponents((Container) component));
        }
    }
    return result;
}

You need to replace the following code:

Component[] component =((ExampleTab1)obj).getContentPanel().getComponents();
with this code:
List<Component> components = getAllComponents(((ExampleTab1)obj).getContentPanel());
and don't forget the null check for the getName() function, if you have components without name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top