1

I have this code by which I am trying to count/get the number of jbuttons present on jframe

I have 7 jbuttons and 2 jtext fields on jframe but Output is coming 1

Component c=this;
Container container = (Container) c;
int x = container.getComponentCount();
System.out.println(x);

Can I get some guidance

user2747954
  • 97
  • 1
  • 5
  • 16

4 Answers4

2

Get all the components in the JFrame(hint: use recursion as done here).

public static List<Component> getAllComponents(final Container c) {
    Component[] comps = c.getComponents();
    List<Component> compList = new ArrayList<Component>();
    for (Component comp : comps) {
      compList.add(comp);
      if (comp instanceof Container) {
        compList.addAll(getAllComponents((Container) comp));
      }
    }
    return compList;
  }

Then test for the components that are jbuttons.

int count =0;
for(Component c : getAllComponents(container)){
  if(c instanceof JButton) count++;
}
Grammin
  • 11,808
  • 22
  • 80
  • 138
1

Try to change your first line:

Component c = (your JFrame object);
Arash Saidi
  • 2,228
  • 20
  • 36
1

You can use Darryl's Swing Utils to recursively search Containers for components.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

Sounds like you'd be better counting the components in the hierarchy rather than on a single component, for example:

public static int countSubComponentsOfType(Container container, Class<? extends Component> type){
    int count = 0;
    for(Component component : container.getComponents()){
        if(type.isInstance(component)) count++;
        if(component instanceof Container) 
            count += countSubComponentsOfType((Container)component, type);
    }
    return count;
}

Alternatively, if you genuinely want the components on a JFrame, use the following instead.

frame.getRootPane().getComponentCount();

This is because JFrame always just contains 1 child component, a JRootPane. Anything added to the JFrame is added to the rootpane.

Bobbo
  • 305
  • 1
  • 7