So a section of my assignment is to make a triangle class to be linked to various buttons...but I'm not sure how to make one in eclipse. The specific instructions say this:
Create a triangle class
- Data fields: Point[] coords;
- constructors
- Implement all abstract methods defined in superclass
- Getters and setters for each data field
- Override public void paint(Graphics arg0) method
I have everything set up in the other classes..except for the triangle class. I'm confused on how to create a triangle using an array of points...Do I need to use Point x,y or somehow store 3 (x,y) coordinate pairs in that one array variable coords? I imagine to create it you would use drawPolygon...but I'm not certain. Any tips?
Here is an example class for Triangle
public class Triangle {
private Point[] coords;
// Null object constructor
public Triangle() {
this.coords = null;
}
// Constructor with point array
public Triangle(Point[] coords) {
this.coords = coords;
}
// Constructor with multiple points
public Triangle(Point a, Point b, Point c) {
this.coords = new Point[3];
coords[0] = a;
coords[1] = b;
coords[2] = c;
}
// The actual paint method
public void paint(Graphics arg0) {
// Setup local variables to hold the coordinates
int[] x = new int[3];
int[] y = new int[3];
// Loop through our points
for (int i = 0; i < coords.length; i++) {
Point point = coords[i];
// Parse out the coordinates as integers and store to our local variables
x[i] = Double.valueOf(point.getX()).intValue();
y[i] = Double.valueOf(point.getY()).intValue();
}
// Actually commit to our polygon
arg0.drawPolygon(x, y, 3);
}
}
Not sure what exactly this class is supposed to be extending, so nothing is marked as an override or anything, and it is missing setters and accessors, but you should be able to make it work.
Use the g.drawPolygon
that takes an array of Point
s as it's args.
Did something similar, where I drew a polygon of three sides. Might help..
for (int i = 0; i < 3; i++){
polygon1.addPoint(
(int) (40 + 50 * Math.cos(i * 2 * Math.PI / 3)),
(int) (150 + 50 * Math.sin(i * 2 * Math.PI / 3))
);
}
g.drawPolygon(polygon1);