2012-10-28 66 views
1

所以我的任务的一部分是让一个三角形类链接到各种按钮......但我不知道如何在eclipse中制作一个三角形类。的具体说明这样说:在java中画一个三角形

创建三角形类

  1. 数据字段:点[] COORDS;
  2. 构造
  3. 实现超
  4. getter和setter方法定义的每个数据字段中的所有抽象方法
  5. 覆盖公共无效漆(图形为arg0)方法

我把一切都建立在其他类除三角类外。我很困惑如何使用点数组创建三角形...我是否需要使用Point x,y或以某种方式将3(x,y)坐标对存储在该数组变量坐标系中?我想要创建它,你会使用drawPolygon ...但我不确定。有小费吗?

回答

1

这里是三角

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

不确定的示例类究竟这个类应该被延长,因此没有被标记为一个覆盖或任何东西,它缺少制定者和存取,但你应该能够使其工作。

+0

真棒,这正是我需要的人。我想我现在明白如何制作它。非常感谢:D – user1780311

+0

为什么'x [i] = Double.valueOf(point.getX())。intValue();'?为什么不''x [i] = point.getX();'? – Mordechai

1

使用g.drawPolygon需要一组Point s作为它的参数。

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