0

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");
    }
spysmily1
  • 57
  • 8
  • *"I seriously believe I'm looking at it wrong"* What you're looking at is fragile code that should not be used for study. 1) Why code an applet? If it is due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why AWT rather than Swing? See my answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. – Andrew Thompson Apr 16 '14 at 07:50

1 Answers1

1

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

Braj
  • 46,415
  • 5
  • 60
  • 76
  • How do you trace the hierarchy of these containers? I guess what I'm saying is how do you know those are the parent containers? – spysmily1 Apr 15 '14 at 23:58
  • Its so simple. I printed `this.getParent().getClass().getName()` then I printed `this.getParent().getParent().getClass().getName()`. – Braj Apr 15 '14 at 23:59
  • Okay, I thought there might be a predefined list. Thanks alot! – spysmily1 Apr 16 '14 at 00:06
  • If AppletViewer is a Frame, I don't see why you would need a cast. When I take out the cast, it ends up with the error "cannot convert from Container to Frame". – spysmily1 Apr 16 '14 at 02:19
  • `getParent()` is a method of `Component` class that returns super type `Container` that's why you have to downcast it. The best way is use `instanceof` operator in such condition. – Braj Apr 16 '14 at 07:30
  • I greatly appreciate your help as you have cleared up many problems I didn't know or have overlooked. – spysmily1 Apr 16 '14 at 13:04