尝试在JFrame中绘制线时出现空错误

时间:2015-10-27 20:12:17

标签: java swing

我试图制作一个绘制Kosh Snowflake的递归程序但是当我尝试运行它时会给我一个错误。显然n即使我初始化它也是null:

Line2D n = new Line2D.Double(x0,y0,x1,y1);
        g2.draw(n);

这是完整的程序:

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
    class turtle{
    double direction,x,y;
    public turtle(double direction, double x, double y)
    {
        this.direction=0;
        this.x=0;
        this.y=0;
    }
    public void move(double length)
    {
        this.x=x+Math.sin(direction)*length;
        this.y=y+Math.cos(direction)*length;
    }
    public void rotate(double angle)
    {
        this.direction=angle;
    }
}
public class fractal extends JComponent
{
    turtle t = new turtle(0,0,0);
    Graphics2D g2;
    public static void main(String [] args)
{
    fractal p = new fractal();
    JPanel panel = new JPanel();
    p.fractal(300,3);
    panel.add(p);
    panel.setSize(900,900);
    panel.setVisible(true);
}
public void fractal(double length,double depth)
{
    if(depth==0)
    {
        double x0=t.x;
        double y0=t.y;
        t.move(length/4);
        double x1=t.x;
        double y1=t.y;
        Line2D n = new Line2D.Double(x0,y0,x1,y1);
        g2.draw(n);
        x0=t.x;
        y0=t.y;
        t.rotate(60);
        t.move(length/4);
        x1=t.x;
        y1=t.y;
        g2.draw(new Line2D.Double(x0,y0,x1,y1));
        x0=t.x;
        y0=t.y;
        t.rotate(-60);
        t.move(length/4);
        x1=t.x;
        y1=t.y;
        g2.draw(new Line2D.Double(x0,y0,x1,y1));
        x0=t.x;
        y0=t.y;
        t.rotate(0);
        t.move(length/4);
        x1=t.x;
        y1=t.y;
        g2.draw(new Line2D.Double(x0,y0,x1,y1));
    }
    else
    {
        fractal(length/4,depth-1);
        g2.rotate(60);
        fractal(length/4,depth-1);
        g2.rotate(-60);
        fractal(length/4,depth-1);
        g2.rotate(0);
        fractal(length/4,depth-1);
    }
}
}

1 个答案:

答案 0 :(得分:3)

Graphics2D g2null。 请查看有关绘制JComponents的一些文档,例如“ Performing Custom Painting”。