Question

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?

Was it helpful?

Solution

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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top