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);
}
}
}
运行结果: