tags:

views:

356

answers:

3

Is it possible to get the name of the panel that a JLabel is added to? I added some JLabels to different JPanels, and I want to call different mouse events according to which panel the jLabels are placed upon.

+3  A: 

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

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

Gordon
+1  A: 

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 assumes that the labels are direct children of the JPanels. However, this may not always be the case, sometimes they are great-grandchildren or great-great-grandchildren of the panel. If this is the case, you'll have do some slightly more complex operations to traverse the 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 you don't want to test for equality of the components, you can test for equality of the components' properties:

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

bguiz
thanks that was very helpful :)
Kari
you're welcome...
bguiz
+1  A: 

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

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

Samuel Sjöberg