Drawing a polygon
807597Jan 7 2005 — edited Jan 20 2005Hi, im putting togeather a drawing program and i need a minimum of 4 shapes to draw. So far ive only been able to manage three shapes (Rectangle, Oval & Round Edge Rectangle), ive been trying for ages trying to get i to draw a polygon, but ive had little luck.
Basicly ive stored all my shapes into a nested class (called 'Shape') and i call each shape from here when selected by the user via a menu. Below is a copy of my 'Shape' class, if any1 can help me put in a polygon into this class, than i would be greatful enough to hand out some Duke Dollars.
static abstract class Shape {
int left, top; // Position of top left corner of rectangle that bounds this shape.
int width, height; // Size of the bounding rectangle.
Color color = Color.white; // Color of shape.
boolean drawOutline; // If true, a black border is drawn on the shape
void reshape(int left, int top, int width, int height) {
// Set the position and size of this shape.
this.left = left;
this.top = top;
this.width = width;
this.height = height;
}
void setSize(int width, int height) {
// Set the size of this shape
this.width = width;
this.height = height;
}
void moveBy(int dx, int dy) {
left += dx;
top += dy;
}
void setColor(Color color) {
this.color = color;
}
void setDrawOutline(boolean draw) {
// If true, a black outline is drawn around this shape.
drawOutline = draw;
}
boolean containsPoint(int x, int y) {
if (x >= left && x < left+width && y >= top && y < top+height)
return true;
else
return false;
}
abstract void draw(Graphics g);
} // end of class Shape
static class RectShape extends Shape {
// This class represents rectangle shapes.
void draw(Graphics g) {
g.setColor(color);
g.fillRect(left,top,width,height);
if (drawOutline) {
g.setColor(Color.black);
g.drawRect(left,top,width,height);
}
}
}
static class OvalShape extends Shape {
// This class represents oval shapes.
void draw(Graphics g) {
g.setColor(color);
g.fillOval(left,top,width,height);
if (drawOutline) {
g.setColor(Color.black);
g.drawOval(left,top,width,height);
}
}
boolean containsPoint(int x, int y) {
// Check whether (x,y) is inside this oval, using the
// mathematical equation of an ellipse.
double rx = width/2.0; // horizontal radius of ellipse
double ry = height/2.0; // vertical radius of ellipse
double cx = left + rx; // x-coord of center of ellipse
double cy = top + ry; // y-coord of center of ellipse
if ( (ry*(x-cx))*(ry*(x-cx)) + (rx*(y-cy))*(rx*(y-cy)) <= rx*rx*ry*ry )
return true;
else
return false;
}
}
static class RoundRectShape extends Shape {
// This class represents rectangle shapes with rounded corners.
void draw(Graphics g) {
g.setColor(color);
g.fillRoundRect(left,top,width,height,width/3,height/3);
if (drawOutline) {
g.setColor(Color.black);
g.drawRoundRect(left,top,width,height,width/3,height/3);
}
}
}
} // end class ShapeDraw