Drawing a triangle in java

2019-08-02 18:52发布

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

  1. Data fields: Point[] coords;
  2. constructors
  3. Implement all abstract methods defined in superclass
  4. Getters and setters for each data field
  5. 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?

3条回答
混吃等死
2楼-- · 2019-08-02 19:16

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.

查看更多
beautiful°
3楼-- · 2019-08-02 19:18

Use the g.drawPolygon that takes an array of Points as it's args.

查看更多
何必那么认真
4楼-- · 2019-08-02 19:24

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);
查看更多
登录 后发表回答