java - 如何在java中使用点画线?

标签 java arraylist

我想知道如何使用 Java 中的不同点来画一条线。这是我到目前为止的代码。我宁愿不获取每个点的 x 和 y,而只是让程序自行使用 x、y 中的点。我对编程还很陌生,目前不太擅长使用 javadoc。以下是我现在的代码:

 //Create a Polygon class. A polygon is a closed shape with lines joining the corner points. 
 //You will keep the points in an array list. Use object of java.awt.Point for the point.

 //Polygon will have as an instance variable an ArrayList of Points to hold the points
 //The constructor takes no parameters but initializes the instance variable.  The
 //Polygon class also has the following methods:
 //    add: adds a Point to the polygon
 //    perimeter: returns the perimeter of the polygon
 //    draw: draws the polygon by connecting consecutive points and then
 //          connecting the last point to the first.
 //
 //No methods headers or javadoc is provided this time. You get to try your hand at writing
 //a class almost from scratch

 // Need help starting this question? In the lesson titled
 // "Starting points: Problem Set Questions", go to the
 // problem titled "Problem Set 6 - Question 3" for some tips on 
 // how to begin.

 import java.util.ArrayList; import java.awt.Point;

 public class Polygon {
     ArrayList<Point> points;

     /**
     **  a Polygon represents a shape with flat lines and several points.
     */ 
     public Polygon(){
     /**
     * Constructs empty array of points.
     */
     points = new ArrayList<Point>();
     }    /**    ** Adds points to the polygon points Array.    *@param = points x and y coordinates to add to class    */
     public void addPoints(Point point){
         points.add(point);
     }
     /**
     **gets distance between points in ArrayList
     */
     public double perimeter(){
         double perimeter = 0;
         int i = 0;
         while(i<points.size()){
             if(i<points.size()-1){
              perimeter = perimeter + points.get(i).distance(points.get(i+1));   
             }
             else{
              perimeter = perimeter + points.get(i).distance(points.get(0));   
             }
         }
         return perimeter;
     }
      /**    * Draws Polygon using points from points ArrayList    */
     public void drawPolygon(){
      int i = 0;
         while(i < points.size()-1){
           Line2D line = Line2D.Float(points.get(i), points.get(i+1));
             line.draw();
         }
         Line2D lastLine = Line2D.Float(points.get(0), points.get(points.size()-1));
         lastLine.draw();
     } }

最佳答案

让我正确理解一下,您想要实现 draw() 方法吗?

如果是这样,您需要做的是搜索 Bresenham 算法,该算法根据两个给定点绘制一条线。

关于java - 如何在java中使用点画线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35174170/

相关文章:

java - 将数据添加到 ArrayList 并删除旧的

java - 验证 ArrayList 的元素以匹配参数 (Java)

Java:实现类似问题

java - 如何将 Google OAuth 限制到特定的 Google Apps 域

Java JITC native 代码生成/执行示例?

java - Google Fit dataRead 返回状态 TIMEOUT

java - 从 Android 应用程序进行 NFC 打印

java - 使用 Eclipse 内存分析器分析堆转储

java - 如何比较两个有序列表

java - 使用对象的字段过滤 ArrayList