Java Class Cast Exception java.awt.geom.Path2D.Double

扶醉桌前 提交于 2020-01-05 02:46:32

问题


I've been getting this class cast exception when trying to to implement an AffineTransform.

Call to AffineTransform:

public Shape moveToAndRotate(double x, double y, double theta)
{
    double cx = getBounds2D().getCenterX();
    double cy = getBounds2D().getCenterY();

    at.translate(cx, cy);
    at.translate(x, y);
    at.rotate(Math.toRadians(theta));
    at.translate(-cx, -cy);
    return at.createTransformedShape(yingYang);
}

This is resides in a custom shape class (YingYang).

public class YingYang implements Shape
{
    private Area yingYang = new Area();
    private AffineTransform at = new AffineTransform();
    ...
}

When ever I make a call I get a class cast exception when I try to cast this back to a YingYang either from the drawing panel or within the class it self (if I change the return type to YingYang.

I make the call like this:

YingYang newShape = (YingYang) shape.moveToAndRotate(newLoc1.x, newLoc1.y, theta);

This is the error:

java.lang.ClassCastException: java.awt.geom.Path2D$Double cannot be cast to Animation.YingYang

Any ideas since YingYang implements shape one would think that I shouldn't have to cast this at all. Am I missing a key concept?


回答1:


You are getting a class cast exception because you can only go up the inheritance tree. Meaning YinYang is a Shape but a Shape isnt necessarily a YinYang. createTransformedShape is returning a Path2D which is a Shape. But that Shape is not a YinYang.

You could either keep the variable yinYang = new Area(); inside your YinYang class or make your YinYang extend the area.

So intead of YinYang -> has an Area. It would be YinYang -> is an Area

If you really need to leave the extends inheritance open you can implement a shape and implement all the methods to go to the yinYang variable.

Then make a constructor like the following

private class YinYang extends Area {
    public YinYang(Shape shape) {
        super(shape);
    }
}

public Shape moveToAndRotate(double x, double y, double theta)
{
    double cx = getBounds2D().getCenterX();
    double cy = getBounds2D().getCenterY();

    at.translate(cx, cy);
    at.translate(x, y);
    at.rotate(Math.toRadians(theta));
    at.translate(-cx, -cy);
    return at.createTransformedShape(yingYang);
}

YingYang shape = new YingYang(shape.moveToAndRotate(newLoc1.x, newLoc1.y, theta));


来源:https://stackoverflow.com/questions/19614244/java-class-cast-exception-java-awt-geom-path2d-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!