2015-10-27 64 views
-1

我試圖繪製一個Kosh Snowflake的遞歸程序,但在嘗試運行時出現錯誤。顯然,n爲空,即使我初始化:嘗試在JFrame中繪製線條時發生空錯誤

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); 
    } 
} 
} 
+3

您的graphics2D對象爲空,這就是爲什麼它不起作用。你需要通過擺動教程,並學習如何做自定義繪畫:http://www.mathcs.duq.edu/simon/Java6/uiswing/14painting/index.html – ControlAltDel

+0

@ControlAltDel Java 6? – MadProgrammer

+1

查看[在AWT和Swing中繪畫](http://www.oracle.com/technetwork/java/painting-140037.html)和[執行自定義繪畫](http://docs.oracle.com/ javase/tutorial/uiswing/painting /)瞭解更多關於如何在Swing/AWT中繪畫的細節 – MadProgrammer

回答

相關問題