moonlight moonlight - 2 years ago 134
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()

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

case 1:
// draw line

// 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

case 3:
// draw Oval


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


Answer Source

Move the draw call to the paint method:

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

    if(shapetype != null) {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download