【问题标题】:Drawing a triangle in java在java中绘制三角形
【发布时间】:2012-10-17 20:59:43
【问题描述】:

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

创建一个三角形类

  1. 数据字段:Point[] 坐标;
  2. 构造函数
  3. 实现超类中定义的所有抽象方法
  4. 每个数据字段的获取器和设置器
  5. 覆盖公共 void paint(Graphics arg0) 方法

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

【问题讨论】:

    标签: java geometry awt java-2d


    【解决方案1】:

    使用g.drawPolygon,它将Points 的数组作为参数。

    【讨论】:

      【解决方案2】:

      这是一个三角形的示例类

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

      不确定这个类到底应该扩展什么,所以没有任何东西被标记为覆盖或任何东西,它缺少设置器和访问器,但你应该能够让它工作。

      【讨论】:

      • 太棒了,这正是我需要的家伙。我想我现在明白如何制作了。非常感谢:D
      • 为什么是x[i] = Double.valueOf(point.getX()).intValue();?为什么不x[i] = point.getX();
      【解决方案3】:

      做了类似的事情,我画了一个三边形的多边形。可能有帮助..

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

      【讨论】:

        猜你喜欢
        • 2014-11-18
        • 2021-11-07
        • 1970-01-01
        • 2014-12-10
        • 1970-01-01
        • 1970-01-01
        • 2013-05-02
        • 1970-01-01
        • 2012-08-13
        相关资源
        最近更新 更多