Java类强制转换异常java.awt.geom.Path2D.Double [英] Java Class Cast Exception java.awt.geom.Path2D.Double
问题描述
在尝试实现AffineTransform时,我一直在收到此类强制转换异常.
I've been getting this class cast exception when trying to to implement an AffineTransform.
调用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);
}
这位于自定义形状类(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.
我这样拨打电话:
YingYang newShape = (YingYang) shape.moveToAndRotate(newLoc1.x, newLoc1.y, theta);
这是错误:
java.lang.ClassCastException:java.awt.geom.Path2D $ Double无法转换为Animation.YingYang
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?
推荐答案
您将收到一个类强制转换异常,因为您只能向上继承树.意思是阴阳是一个形状,但形状不一定是阴阳. createTransformedShape返回的Path2D是Shape.但是那个Shape不是阴阳.
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.
您可以保留变量yinYang = new Area();在您的YinYang班级内部,或者让您的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
如果确实需要打开扩展继承,则可以实现形状并实现所有方法以使用yinYang变量.
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));
这篇关于Java类强制转换异常java.awt.geom.Path2D.Double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!