0

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?

  • Is Polygon extends Shape? If so, Rectangle also extends Shape. You cannot cast Rectangle into Polygon even those in reality, Rectangle is four sides Polygon. You will need to convert Rectangle into Polygon by the look of your structure. Hopes this help. – Minh Kieu May 01 '16 at 19:15
  • Sorry, problem solved-I found a solution! – Super-Coder33 May 01 '16 at 19:35
  • 1
    Nice. Please answer your own question to share it to others. Thx – Minh Kieu May 01 '16 at 19:38

2 Answers2

1

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?

Community
  • 1
  • 1
Martin Frank
  • 3,445
  • 1
  • 27
  • 47
1

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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138