tags:

views:

120

answers:

2

I have a Component which I am using both in a standalone Java application as well as in a Java applet. How can I figure out from within the Component whether my component is in an applet?

Also, once I figure out that I'm running in an Applet, how can I get access to the Applet?

+2  A: 

I think you should be able to do it by repeatedly calling Component.getParent() until you get to the top of the container tree, and then checking whether that container is an instanceof Applet.

The code below is completely untested:

boolean isInAnApplet(Component c)
{
    Component p = c.getParent();
    if (p != null) {
         return isInAnApplet(p);
    } else {
         return (c instanceof Applet);
    }
}
Alnitak
+3  A: 

You can do it without recursion by SwingUtilities.getAncestorOfClass

Dennis Cheung
There is also SwingUtilities.getRoot.
Tom Hawtin - tackline
ooh, nice as well.
Epaga