[英]Null error when trying to draw line in JFrame
I'm trying to make a recursive program that draws a Kosh Snowflake but but gives me an error when I try to run it. 我正在尝试制作一个绘制Kosh Snowflake的递归程序,但是当我尝试运行它时却给了我一个错误。 Apparently n is null even though I initialize it: 即使我将其初始化,显然n为null:
Line2D n = new Line2D.Double(x0,y0,x1,y1);
g2.draw(n);
And here is the full program: 这是完整的程序:
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);
}
}
}
The Graphics2D g2
is null
. Graphics2D g2
为null
。 Please have a look at some documentation about drawing JComponents, eg " Performing Custom Painting ". 请查看有关绘制JComponents的一些文档,例如“ Performing Custom Paint ”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.