1. 程式人生 > >謝爾賓斯基三角形(加入拉桿控制遞迴)

謝爾賓斯基三角形(加入拉桿控制遞迴)

package 三角形;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
//實現謝爾賓斯基三角形
public class sanjiaoxing extends JFrame{
	final JSlider js=new JSlider(1,10,1);//外部定義欄杆引數
	int x1,x2,y1,y2,x3,y3,count;
	int width=600,height=400;
	Graphics g;
	JPanel jp;
	Dimension di;
	
	

	public void showUI(){
		this.setSize(width,height);
		this.setTitle("三角形");
		this.setVisible(true);
		
		//建立流式佈局
		FlowLayout fl = new FlowLayout();
		this.setLayout(fl);
		
		//增加一個拉桿控制
		count = js.getValue();
		this.add(js);
		js.addChangeListener(new ChangeListener() {
			
			@Override
			public void stateChanged(ChangeEvent b) {
				// TODO Auto-generated method stub
//				count = js.getValue();
			}
		});
		
		this.setDefaultCloseOperation(3);

		g=this.getGraphics();
		//加上自定義的滑鼠事件監聽器:滑鼠釋放時呼叫方法
		this.addMouseListener(new MouseAdapter() {
			//只需要重寫需要的方法即可,因為父類不是介面:
			//滑鼠按下時的點的座標
			public void mouseReleased(MouseEvent e) {
				draw(e);
			}
		});
		
	}
	
	//設定基本引數
	public  void draw(MouseEvent e) {
		x1=width/4;
		y1=height*4/5;
		x2=width*3/4;
		y2=height*4/5; 
        g.setColor(java.awt.Color.BLUE);
		draw_digui(x1,y1,x2,y2,js.getValue());
		
	}
	
	
	public void draw_digui(int x1,int y1,int x2,int y2,int count){
		
		if(count>0){
			x3=(int)Math.abs(x2+x1)/2;
			y3=(int) Math.abs(y2-Math.sqrt(3)*Math.abs(x2-x1)/2);
			g.drawLine(x1,y1,x2,y2);
			g.drawLine(x1,y1,x3,y3);
			g.drawLine(x2,y2,x3,y3);
			count--;
			int x11=(x1+x2)/2;
			int y11=(y1+y2)/2;
			int x22=(x2+x3)/2;
			int y22=(y2+y3)/2;
			int x33=(x1+x3)/2;
			int y33=(y1+y3)/2;
		
			g.drawLine(x11,y11,x22,y22);
			g.drawLine(x11,y11,x33,y33);
			g.drawLine(x22,y22,x33,y33);
			draw_digui(x1,y1,x11,y11,count);
			draw_digui(x11,y11,x2,y2,count);
			draw_digui(x33,y33,x22,y22,count);
		}
		count--;
	}
	//主函式入口
	public static void main (String []args){
		sanjiaoxing san = new sanjiaoxing();
		san.showUI();
		
	}
	
}