简体   繁体   中英

Swing: Getting a component's parent from another class

I have a main class, where all my gui components are made called Math.java. In a separate class (Calc), I get all of the components and save them in local components from Math in the constructor of Calc. The only thing that doesn't work is when I try to get the parent component of one of the components, it always returns null. When I directly access the JLabels in Math, it works.

cards[] is an array of JLabels. panel2a and layer are JPanels.

 public void clear()
{
    for(int i =0;i <cards.length; i++)
    {
//this works, calling the components directly
        if(math.cards[i].getParent().equals(math.panel2a) )
        {
            math.panel2a.remove(cards[i]);

            layer.add(cards[i]);

            layer.repaint();
        }
//this doesn't work, using the local components
        if(cards[i].getParent().equals(panel2a) )
        {
            panel2a.remove(cards[i]);

            layer.add(cards[i]);

            layer.repaint();
        }
   }
}

If the two arrays do in fact hold references to the same object, then there is no way (that I know of) for any of that object's methods to behave differently depending on where the object reference is stored. In other words, if it's the same object, then math.cards[i] == cards[i] and there is absolutely no way that you'll get different results depending on whether you call math.cards[i].anyMethod() or cards[i].anyMethod() .

Since you are seeing different results, the arrays must not have the same objects. You probably haven't added the contents of the local cards array to any container. Also keep in mind that when you add a component to one container, that component automatically gets removed from any container it might already be in.

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