Search code examples
javaswingjlabel

Why does a JLabel Component not convert into a JLabel, yet doesn't give any errors?


Okay, so I have this JFrame frame and I'm trying to load all of the components into a JLabel ArrayList. the frame has a LayeredPane and around 20 JLabels scattered across. Some of them have a different z-index/layer index

   ArrayList<JLabel> labelList = new ArrayList<>();
    
    for(Component i : frame.getComponents() ) {
        
        
        if (i instanceof JLabel) {
            labelList.add((JLabel) i);
        }
    }
    
    System.out.println(labelList);

but when I try to print out the ArrayList, it just prints an empty Array.

When I hover over the .getComponents(), it actually shows that all of the JLabels are in fact contained in the method.

And it doesn't give out any errors either, like Component not being able to convert to JLabel etc.

edit: I did as @camickr suggested, and it show that only the contentPane is grabbed. I probably misunderstood how the .getComponents() works.

edit2 just changed the code to:

    ArrayList<JLabel> labelList = new ArrayList<>();
    
    for(Component i : layeredPane.getComponents() ) { //layeredPane being the name of the JLayeredPane, suprisingly

            labelList.add((JLabel) i); 
    }
    
    System.out.println(labelList.toArray().length);

And it works. I am a very dumb indiviudal.


Solution

  • ArrayList<JLabel> labelList = new ArrayList<>();
    
    for(Component i : layeredPane.getComponents() ) { //layeredPane being the name of the JLayeredPane, suprisingly
    
            labelList.add((JLabel) i); 
    }
    
    System.out.println(labelList.toArray().length);
    

    is the solution. It didn't work due to me trying to grab everything from the frame, but the only thing on the frame was the layered Pane, where all the other components were.