我试图将Shape变成多边形。我的代码看起来像这样:
类MyGraphicMethods扩展了Graphics
{
......
...
public void fillShape(Shape S)
{
g.fillPolygon((多边形)S);
}
当我跑步时
public static void main(String [] args){
Shape S = new Rectangle(new Dimension(10,100));
多边形P =(多边形)S;
}
我得到了ClassCastException。 有人能帮助我吗?
答案 0 :(得分:0)
你不能明确地转换你的形状,但你可以使用路径迭代器从形状重新创建它
Poligon p = ....
Shape s = p;
PathIterator iter = s.pathIterator();
我不想解释整个路径迭代器的东西,它已经被解释为Using PathIterator to return all line segments that constrain an Area?
答案 1 :(得分:0)
使用
extends Graphics2D
Graphics g = (Graphics2D) graphics;
g.fill(shape); // Or possibly fill(shape);
在java的历史中,有一点图形由Graphics2D扩展,为了向后兼容,图形保留在API中。但总有人可以将Graphics转换为Graphics2D。
因此,扩展Graphics或Graphics2D并不是一个好主意。 这实际上是我第一次看到这个。