javaappletappletviewer

Understanding the getParent method for a Java applet


I'm trying out a tutorial that uses a class which inherits from the Applet class. I'm having difficulty grasping the concept of the line which creates a frame object. I'm not sure what the 2 getParent() calls do.

Does the first getParent() call reference the StartingClass's parent which is Applet? Does the second getParent() call reference the Applet's parent which is Panel?

I seriously believe I'm looking at it wrong and am looking for clarification.

public class StartingClass extends Applet implements Runnable {

    @Override
    public void init() {

        setSize(800, 480);
        setBackground(Color.BLACK);
        setFocusable(true);
        Frame frame = (Frame) this.getParent().getParent();
        frame.setTitle("Q-Bot Alpha");
    }

Solution

  • The first getParent will return sun.applet.AppletViewerPanel and second will return sun.applet.AppletViewer.

    Here is the declaration of AppletViewer class

    public class sun.applet.AppletViewer extends java.awt.Frame ...
    

    That's why you can downcast AppletViewer into Frame.

    I think, You are mixing getParent() method with the inheritence. Here parent means the parent container of this component not component's immediate super-class.

    For more info have a look at Component#getParent().