JLabel - get parent panel?

后端 未结 3 1237
情深已故
情深已故 2020-12-18 00:32

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 whic

3条回答
  •  -上瘾入骨i
    2020-12-18 01:04

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

提交回复
热议问题