尝试使用for循环绘制A SierpinskiTriangle的applet代码

时间:2015-02-24 21:19:11

标签: java geometry

大家好,所以我正在尝试编写一个代码,当我运行它时会绘制一个SierpinskiTriangle。该程序必须有一个我已经拥有的for循环但我在尝试使程序complile时遇到问题。它说double不能转换为Point2D任何人都可以帮我这个吗?

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Line2D;

public class ST extends JFrame {

    int N = 50000;
    double sqrt3 = Math.sqrt(3);
    double x = 0.0, y = 0.0; 

public static void main(String args[]) {
    ST t = new ST();
    t.add(new JComponent() {
        public void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
            for (int i = 0; i < N; i++) {
                double r = Math.random();
                double x0, y0;

                if (r < 1./3.) {
                    x0 = 0.0; y0 = 0.0;
                } else if (r < 2./3.) {
                    x0 = 0.0; y0 = 2.0 ; 
                } else {
                    x0 = sqrt3; y0 = 1.0;
                }
                double x = (x0 + x) / 2;
                double y = (y0 + y) / 2;  

                Shape l = new Line2D.Double(x,y);
                g2d.draw(l);

            }
        }
    });

    t.setDefaultCloseOperation(EXIT_ON_CLOSE);
    t.setSize(220, 300);
    t.setVisible(true);
}
}

1 个答案:

答案 0 :(得分:0)

正如http://docs.oracle.com/javase/7/docs/api/java/awt/geom/Line2D.Double.html上的Java API所说,类Line2D.Double有两个构造函数:

Line2D.Double(double x1, double y1, double x2, double y2)

Line2D.Double(Point2D p1, Point2D p2)

因为您指定了两个参数,所以java编译器会假设后者。