【发布时间】:2015-05-02 13:25:39
【问题描述】:
首先,我制作了一个“游戏渲染器”。
我的问题是,当我需要绘制当前元素时:我需要知道它是矩形、圆形还是图像等等。
我的类(矩形、圆形...)是从 Graphic 扩展而来的。
public class Rectangle extends Graphic {...}
如果我想画它们,我会在列表中查看ArrayList<Graphic>
for(index = 0;index < graphicObjects.size();index++){
currentElement = graphicObjects.get(index);
if(currentElement instanceof Rectangle) { // Here is an error.
Rectangle r = (Rectangle) currentElement;
// here the drawing.
}
}
感谢您的帮助(Goggle 没有帮助):)
编辑:
错误是:“不兼容的条件操作数类型图形和矩形”
以及为什么我需要知道类型: 我的代码:
public static Image getImage(Graphics g,int width, int height) {
int imgWidth = width;
int imgHeight = height;
BufferedImage bfImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = bfImage.getGraphics();
for (int index = 0; index < grObjList.size(); index++) {
Graphic gr = grObjList.get(index);
if(gr instanceof Rectangle){
graphics.setColor(gr.color);
graphics.fillRect(gr.x, gr.y, gr.width, gr.height);
}
}
return bufferedImagetoImage(bfImage);
}
【问题讨论】:
-
错误是什么?
-
为什么需要知道类型?虚拟方法和继承的重点是您不需要知道类型。只需创建一个绘图函数并在子类中覆盖它...
-
一般来说,你应该遵循上面 nneonneo 建议的做法和 pathfinderelite 的回答。但是,如果您使用 eclipse,为了解开这个谜,请在此处查看投票最多的答案:stackoverflow.com/questions/2551337/…
-
检查您的导入。很可能您导入了错误的 Rectangle。
标签: java extends instanceof