javaswingjmenujpopupmenu

Swing JComponent.getComponentCount() is always returning 0


I'm confused why this is happening. Ultimately I want to have logic to test the component at index 0, but first I need this method to return accurately. Here is a sample of the code I have that is returning 0:

    parentComp.add(saveAsItem);
    parentComp.add(saveItem);
    if(manager.getListConfigurations().size() > 0){
        parentComp.add(loadMenu);
        parentComp.add(removeMenu);
    }
    System.out.println("COUNT: " + parentComp.getComponents().length);

That println statement always returns 0. I would think it should either return 2 or 4, depending on if the above condition is met.

This is very strange behavior. I can't seem to understand why it is happening.

Edit

If I do the following, I get an exception:

parentComp.getComponent(0).getClass().getName();

java.lang.ArrayIndexOutOfBoundsException: No such child: 0

so it clearly doesn't think there are any children, yet there are. I'm adding them right there.

Edit 2

I'm using a class declared as a JComponent, but which gets implemented as either a JMenu or JPopupMenu depending on conditions. In this case, it's been declared as a JMenu. Maybe it's weird JMenu behavior?


Solution

  • I'm using a class declared as a JComponent, but which gets implemented as either a JMenu or JPopupMenu depending on conditions. In this case, it's been declared as a JMenu. Maybe it's weird JMenu behavior?

    Presuming you are adding JMenuItem's to a JMenu, a JMenu deals with addition of JMenuItem's differently because they are added to an underlying JPopupMenu, so you should get the JPopupMenu of the JMenu and count the items contains within this Container. For example:

    JPopupMenu menu1 = new JPopupMenu();
    menu1.add(new JMenuItem("Item1"));
    menu1.add(new JMenuItem("Item2"));
    countItems(menu1);
    JMenu menu2 = new JMenu();
    menu2.add(new JMenuItem("Item1"));
    menu2.add(new JMenuItem("Item2"));
    countItems(menu2.getPopupMenu());//Use the JPopupMenu rather than the JMenu itself)
    
    private static final void countItems(JPopupMenu menu){
        System.out.println("COUNT: " + menu.getComponents().length);
    }