Shape类有一个抽象的绘制,它带有一个Graphics对象...例如,如果我想绘制一个矩形,在我写的情况下为2:
shapetype.draw(g); // he said that g is undefined
我应该如何初始化g以调用函数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); }
}
答案 0 :(得分:1)
将绘制调用移至paint
方法:
@Overrride // since you're overriding.
public void paint(Graphics g) {
super.paint(g);
if(shapetype != null) {
shapetype.draw(g);
}
}
仅绘制一次形状是不够的,每次调用paint
时都会被覆盖,因此需要重新绘制。