moonlight moonlight - 7 months ago 25
Java Question

Call a method which has Graphics g as its parameters

Shape class has an abstract draw which takes a Graphics object... for example, if I want to draw a rectangle, in case 2 when I write:

shapetype.draw(g); // he said that g is undefined


how should I initialise g in order to call function draw(g):

public class main extends Applet
{
Shape shapetype; // shapeClass has 3 subclasses

public void init()
{
super.init();

// ask user to choose the type of shape 1-line 2-rectangle 3-oval
// int choice = the type of shape
switch(choice)
{

case 1:
// draw line
break;

// draw Rectangle
case 2:
//ask user for x,y,width and height
shapetype = new Rectangle(x1,y1,w,h);
shapetype.draw(g); // to draw a rectangle
break;

case 3:
// draw Oval
break;

default:
break;
}
}

public void paint(Graphics g)
{super.paint(g); }

}

Answer

Move the draw call to the paint method:

@Overrride // since you're overriding.
public void paint(Graphics g) {
    super.paint(g);

    if(shapetype != null) {
        shapetype.draw(g);
    }
}

Drawing the shape only once will not be enough, it will get overwritten each time paint is called, so it needs to be redrawn.

Comments