Tuesday, March 15, 2011

How to tell if my Java component is in an Applet?

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?

From stackoverflow
  • 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);
        }
    }
    
  • You can do it without recursion by SwingUtilities.getAncestorOfClass

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

0 comments:

Post a Comment