java 科赫雪花

package SRC;
//MainFrame.java
import java.awt.*;
import javax.swing.*;

public class MainFrame extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public Toolkit kit = Toolkit.getDefaultToolkit();
	public Dimension screenSize = kit.getScreenSize();
	public int depth = 10;
	public static JLabel JL = new JLabel("Depth : ");
	public static JTextField JF = new JTextField("3",10);
	public static JPanel JP = new JPanel();

	public MainFrame(String title,int width, int height) {
		super(title);
		setSize(width,height);
		int screenw = screenSize.width;
		int screenh = screenSize.height;
		setLocation((screenw - width) / 2, (screenh - height) / 2);	
	}
	public static void main(String[] args) {
		MainFrame MF = new MainFrame("Koch Snowflake",1500,1200);
		MF.setVisible(true);
		MF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		KochSnowflakePanel KSP = new KochSnowflakePanel(3);
		JF.addActionListener((e) -> {
			KSP.setDepth(Integer.parseInt(JF.getText()));
		});
		MF.add(KSP,BorderLayout.CENTER);
		JP.add(JL,BorderLayout.SOUTH);
		JP.add(JF,BorderLayout.SOUTH);
		MF.add(JP,BorderLayout.SOUTH);
		KSP.repaint();
	}
}
package SRC;
//KochSnowflakePanel.java
import java.awt.*;
import javax.swing.*;

public class KochSnowflakePanel extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public int depth;
	
	public KochSnowflakePanel(int depth) {
		this.depth = depth;
	}
	public void setDepth(int depth) {
		this.depth = depth;
		repaint();
	}
	public void paint(Graphics g) {
		super.paint(g);
		int side = (int) (getHeight() * 0.7);
		int high =(int)(side*Math.cos(Math.toRadians(30)));
		Point A = new Point(getWidth() / 2,10);
		Point B = new Point(getWidth() / 2 - side / 2, 10 + high);
		Point C = new Point(getWidth() / 2 + side / 2, 10 + high);
		PaintKochSnowFlake(g, depth, A, B);
		PaintKochSnowFlake(g, depth, B, C);
		PaintKochSnowFlake(g, depth, C, A);
	}
	private void PaintKochSnowFlake(Graphics g,int depth,Point p1,Point p2) {
		if(depth == 0){
			g.drawLine(p1.x, p1.y,p2.x, p2.y);
		}else{
			int ΔX = p2.x - p1.x;
			int ΔY = p2.y - p1.y;
			Point D = new Point(p1.x + ΔX / 3, p1.y + ΔY / 3);
			Point E = new Point(p1.x + ΔX * 2 / 3, p1.y + ΔY * 2 / 3);
			Point F = new Point(
					(int)((p1.x + p2.x) / 2 + Math.sin(Math.toRadians(60)) * (p1.y - p2.y) / 3),
					(int)((p1.y + p2.y) / 2 + Math.sin(Math.toRadians(60)) * (p2.x - p1.x) / 3));
			PaintKochSnowFlake(g, depth - 1, p1, D);
			PaintKochSnowFlake(g, depth - 1, D, F);
			PaintKochSnowFlake(g, depth - 1, F, E);
			PaintKochSnowFlake(g, depth - 1, E, p2);
		}
	}
}

运行结果:

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值