在java中绘制一个三角形

时间:2012-10-28 05:03:34

标签: java geometry awt java-2d

因此,我的任务的一部分是将三角形类链接到各种按钮......但我不确定如何在日食中制作一个。具体说明如下:

  

创建三角形类

     
      
  1. 数据字段:Point [] coords;
  2.   
  3. 施工人员
  4.   
  5. 实现超类中定义的所有抽象方法
  6.   
  7. 每个数据字段的getter和setter
  8.   
  9. 覆盖public void paint(Graphics arg0)方法
  10.   

我在其他类中设置了所有内容。除了三角形类。我对如何使用点数组创建三角形感到困惑...我是否需要使用Point x,y或以某种方式在该一个数组变量coords中存储3(x,y)坐标对?我想创建它你会使用drawPolygon ...但我不确定。有什么提示吗?

3 个答案:

答案 0 :(得分:1)

使用带有g.drawPolygon数组的Point作为它的参数。

答案 1 :(得分:1)

以下是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);
  }
}

不确定这个类究竟应该扩展到什么,所以没有任何标记为覆盖或任何东西,并且它缺少setter和accessors,但你应该能够使它工作。

答案 2 :(得分:1)

做了类似的事情,我绘制了三面的多边形。可能会帮助..

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);