简体   繁体   English

Java-instanceof

[英]Java - instanceof

First off all, I made a "Game-Renderer". 首先,我做了一个“游戏渲染器”。

My problem is that, when I need to draw the current Element: I need to know if it's a Rectangle, Circle, or an Image and so on. 我的问题是,当我需要绘制当前Element时:我需要知道它是Rectangle,Circle还是Image等。

My Classes (Rectangle, Circle,...) are extending from Graphic. 我的课程(矩形,圆形等)是从图形学扩展的。

public class Rectangle extends Graphic {...}

And if I want to draw them I look in the List ArrayList<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.
    }
}

Thanks for helping (Goggle wasn't helpful) :) 感谢您的帮助(Goggle没有帮助) :)

Edit: 编辑:

Error is: "Incompatible conditional operand types Graphic and Rectangle" 错误为:“条件操作数类型为图形和矩形不兼容”

And why I need to know the type: My code: 以及为什么我需要知道类型:我的代码:

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);
}

To avoid using instanceOf , have Graphic implement an abstract draw method. 为了避免使用instanceOf ,让Graphic实现抽象的draw方法。 Then, override draw in your Rectangle , Circle , etc classes. 然后,在RectangleCircle等类中覆盖draw Then you can do 那你可以做

for(index = 0;index < graphicObjects.size();index++){
    currentElement = graphicObjects.get(index);
    currentElement.draw();
}

You are getting an error because you are trying to say that the supertype Graphic is a Rectangle which is not a Rectangle is a Graphic. 之所以出错,是因为您试图说超型图形是一个矩形,而不是矩形是一个图形。

So make sure you have a function in the super type and override it in the subtypes so you dont need to do any casting. 因此,请确保您在超级类型中具有一个函数,并在子类型中对其进行覆盖,因此您无需进行任何强制转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM