Super-Coder33
Super-Coder33

Reputation: 3

Is it possible to turn a shape into a polygon in java?

I'm trying to make a Shape into a Polygon. My code looks something like this:

class MyGraphicMethods extends Graphics
{
...
...
public void fillShape(Shape S)
{
g.fillPolygon((Polygon)S);
}

When I run

public static void main(String[] args) {
Shape S=new Rectangle(new Dimension(10, 100));
Polygon P=(Polygon)S;
}

I get a ClassCastException. Can Somebody help me?

Upvotes: 0

Views: 1659

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

Use

extends Graphics2D

Graphics2D g = (Graphics2D) graphics;
g.fill(shape); // Or possibly fill(shape);

At one point in java's history Graphics was extended by Graphics2D, and for backward compatibility Graphics remained in the API. However one always can cast Graphics to Graphics2D.

Hence it is not a good idea to extend Graphics, nor Graphics2D. This is in fact the first time I see this.

Upvotes: 1

Martin Frank
Martin Frank

Reputation: 3454

you cannot convert your shape not explicitly back, but you can re-create it from shape using path iterator

Poligon p = ....
Shape s = p;

PathIterator iter = s.pathIterator();

i don't want to explain the whole path-iterator stuff, it's already been explained int Using PathIterator to return all line segments that constrain an Area?

Upvotes: 1

Related Questions