Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JLabel - get parent panel?

Tags:

java

swing

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.

like image 615
Kari Avatar asked Dec 21 '09 07:12

Kari


3 Answers

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.

like image 186
Gordon Avatar answered Nov 15 '22 21:11

Gordon


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").

like image 4
bguiz Avatar answered Nov 15 '22 21:11

bguiz


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).

like image 3
Samuel Sjöberg Avatar answered Nov 15 '22 22:11

Samuel Sjöberg