There are multiple choices, depending on your needs.
If you want to know when any existing component is added to a parent, you can add a HierarchyListener to it and listen for an event of type PARENT_CHANGED which is sent after the component is added to the parent.
Example:
component.addHierarchyListener(new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
if ( (e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) {
if (getParent() == e.getChangedParent()) {
System.out.println("*** Added to parent " + e.getChangedParent());
}
}
}
});
If you are already creating a custom component, you can override the "addNotify()" method:
@Override public void addNotify() {
super.addNotify();
// do something here with getParent();
}
If you want to know about the parent only after the component has been made visible, you can use an AncestorListener. The ancestorAdded(AncestorEvent) will be called every time the component is made visible. For instance, an AncestorListener on a JPanel inside a JTabbedPane will get such an event every time the user selects that tab for display.