代码如下,加入了拉杆控制递推,每次拉杆控制参数变化都会刷新画布
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());
}
}