Koch科赫曲線的實現
阿新 • • 發佈:2018-12-27
程式碼如下,加入了拉桿控制遞推,每次拉桿控制引數變化都會重新整理畫布
package 科赫曲線; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.nio.channels.Pipe; import javax.swing.JFrame; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /* * 科赫曲線的實現 * @author LiuYuliang */ public class kehe extends JFrame { final static JSlider js = new JSlider(1,15,10); private int count; private Graphics g; private double x1,y1,x2,y2; private int width=1000,height=500; double PI=Math.PI; public void showUI(int count){ this.setSize(new Dimension(width,height)); this.setTitle("科赫曲線"); this.setVisible(true); this.setDefaultCloseOperation(3); this.setResizable(false); g=this.getGraphics(); FlowLayout fl = new FlowLayout();//定義佈局 this.setLayout(fl); count=js.getValue(); this.add(js); js.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent b) { update();//拉桿後重新整理畫布 } }); this.addMouseListener(new MouseAdapter() { //只需要重寫需要的方法即可,因為父類不是介面: //滑鼠按下時的點的座標 public void mouseReleased(MouseEvent e) { draw(e); } }); } //定義重新整理方法 public void update(){ repaint(); } //轉換座標系為左下角 為原點 public void draw(MouseEvent e){ x1=width/4; y1=height/4; x2=width*3/4; y2=height/4; draw_digui(g,x1,y1,x2,y2,js.getValue()); } //遞迴函式 public void draw_digui(Graphics g,double x1,double y1,double x2,double y2,int count){ double x3,y3,//第一個三等分點 x5,y5,//第二個三等分點 x4,y4,//頂點 l,theta;//正三角形底邊長和角度 if(count<=1){ g.drawLine((int)x1,height-(int)y1,(int)x2,height-(int)y2);//由於轉換了座標系,所以相應的要轉換會原來以右上角為座標原點的座標系,只需要變化Y的值即可 }else{ //第一個三等分點 x3 = x1+(x2-x1)/3; y3 = y1+(y2-y1)/3; //第二個三等分點 x5= x2-(x2-x1)/3; y5= y2-(y2-y1)/3; //求三角形邊長和三角形底邊的傾斜角 l=Math.sqrt((y5-y3)*(y5-y3)+(x5-x3)*(x5-x3)); theta=Math.atan((y5-y3)/(x5-x3)); //對角的條件的限制 if((theta>=0) && ((x5-x3)<0)||(theta<=0)&&((x5-x3)<0)){ theta=theta+PI; } //頂點 x4=x3+Math.cos(theta+PI/3)*l; y4=y3+Math.sin(theta+PI/3)*l; count--; draw_digui(g,x1,y1,x3,y3,count); draw_digui(g,x3,y3,x4,y4,count); draw_digui(g,x4,y4,x5,y5,count); draw_digui(g,x5,y5,x2,y2,count); } } //主入口 public static void main(String []args){ kehe kh= new kehe(); kh.showUI(js.getValue()); } }