[ACCEPTED]-JLabel - get parent panel?-swing

Accepted answer
Score: 12

If you run label.getParent() it will return the panel the 3 label is inside.

You could then call parent.getName() but 2 the fact the you will now have the object 1 you might not need this now.

Score: 4

The simplest way to do this:

//label1 and label2 are JLabel's
//panel1 and panel2 are JPanel's
doActionsForLabel(label1);
doActionsForLabel(label2);

public void doActionsForLabel(JLabel label)
{
    if (label.getParent() == panel1)
    {
        //do action #1
    }
    else if (label.getParent() == panel2)
    {
        //do action #2
    }
}

The above code 11 assumes that the labels are direct children 10 of the JPanels. However, this may not always 9 be the case, sometimes they are great-grandchildren 8 or great-great-grandchildren of the panel. If 7 this is the case, you'll have do some slightly 6 more complex operations to traverse the 5 parent hierarchy.

public void doActionsForLabel(JLabel label)
{
    boolean flag = true;
    Component parent = label;
    while (flag)
    {
        parent = parent.getParent();
        if ((parent != null) && (parent instanceof JPanel))
        {            
            if (label.getParent() == panel1)
            {
                //do action #1
            }
            else if (label.getParent() == panel2)
            {
                //do action #2
            }            
        }
        else
        {
            flag = false;
        }
    }
}

As Gordon has suggested, if 4 you don't want to test for equality of the 3 components, you can test for equality of 2 the components' properties:

Instead of label.getParent() == panel1, do 1 this or similar instead: label.getParent().getName().equals("panel_1_name").

Score: 3

If you don't know how deep down your label 10 is in the hierarchy, there's some handy 9 functions in SwingUtilities, for example: SwingUtilities.getAncestorOfClass(Class, Component)

An alternative 8 to checking the name of the parent container 7 in your labels could be to simply forward 6 the event to the parent container instead 5 and let the parent do the work. Depending 4 on what you're trying to achieve, it could 3 be useful to decouple the labels from the 2 parents. Forwarding events can be done using 1 Component.processEvent(AWTEvent).

More Related questions