[英]Null error when trying to draw line in JFrame
我正在嘗試制作一個繪制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);
}
}
}
Graphics2D g2
為null
。 請查看有關繪制JComponents的一些文檔,例如“ Performing Custom Paint ”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.