Thursday, January 25, 2007

Common Questions for Lab 2

Question:

Hi, I have a problem for cs10 Lab 2. Not a big problem, but I just
realized that whenever I run my program, it draws a red circle in the
middle of the frame...
Its no big deal, because everything else runs fine, but is there a way
to get rid of it?

Michael

Answer:

Hi Michael,

Yes, there is. It will be easy once I tell you how. But I should also
tell you why it works.

When you make the Alien class extends Ellipse, that means the Alien
itself is an Ellipse .. with some extra ellipses and maybe some
rectangles/lines. Inside the Alien constructor, you probably have a
statement like this...

face = new Ellipse();
face.setSize(...);
face.setLocation(...);

which creates a new Ellipse for variable face, resizes it, and puts it
at some location.

If you didn't call setSize() and setLocation(), what would happen?
Yes, the face will just be a red dot at the middle of the screen...

and that is exactly what is happening to your Alien's ellipse. So, to
fix this problem, you can make use of a special variable called "this"
(without the quotes) .. this refers to the class itself.

Since "this" is already an Ellipse, you do not need to create a new
Ellipse for the face. So, instead of saying

face = new Ellipse();

you can just say
face = this;

and then anything you do with the face, will be performed to the Alien
itself (which is initially a red dot).

Hope this helps!
- Mock

No comments:

Contributors