首先,我做了一个“游戏渲染者”。
我的问题是,当我需要绘制当前元素时:我需要知道它是矩形、圆圈还是图像等等。
我的类(矩形,圆圈,.)从图形上延伸。
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.
    }
}谢谢你的帮助(戈格尔帮不上忙) :)
编辑:
错误是:“不兼容的条件操作数类型为图形和矩形”
以及为什么我需要知道类型:我的代码:
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);
}发布于 2015-05-02 13:30:11
为了避免使用instanceOf,让Graphic实现一个抽象的draw方法。然后,在您的Rectangle、Circle等类中重写Circle。那你就可以
for(index = 0;index < graphicObjects.size();index++){
    currentElement = graphicObjects.get(index);
    currentElement.draw();
}发布于 2015-05-02 13:31:00
您收到了一个错误,因为您试图说超型图形是矩形,而不是矩形是图形。
因此,请确保在超级类型中有一个函数,并在子类型中重写它,这样您就不需要进行任何转换。
https://stackoverflow.com/questions/30002833
复制相似问题