Last active
July 9, 2019 09:52
-
-
Save ahmednasserpro/084db0d2bc4192f546aff9341adc3091 to your computer and use it in GitHub Desktop.
Koch snowflake fractles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.*; | |
import java.awt.event.*; | |
import javax.swing.*; | |
public class KochSnowflake extends JFrame { | |
private KochFrame koch = new KochFrame(); | |
private JTextField tf = new JTextField("0", 5); | |
public KochSnowflake() { | |
JPanel panel = new JPanel(); | |
panel.add(new JLabel("Enter an order: ")); | |
panel.add(tf); | |
add(panel); | |
koch.setSize(400, 474); | |
koch.setLocation(200, 75); | |
koch.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
koch.setVisible(true); | |
tf.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
koch.setOrder(Integer.parseInt(tf.getText())); | |
koch.setVisible(true); | |
} | |
}); | |
} | |
public static void main(String[] args) { | |
JFrame frame = new KochSnowflake(); | |
frame.setSize(200, 100); | |
frame.setLocationRelativeTo(null); | |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
frame.setVisible(true); | |
} | |
} | |
class KochFrame extends JFrame { | |
private int order = 1; | |
public void setOrder(int order) { | |
this.order = order; | |
repaint(); | |
} | |
@Override | |
public void paint(Graphics g) { | |
super.paint(g); | |
Point p1 = new Point(10, getHeight() - 120); | |
Point p2 = new Point(getWidth() - 10, getHeight() - 120); | |
Point p3 = new Point(getWidth() / 2, 40); | |
g.setColor(Color.red); | |
drawLineSegment(g, order, p1, p2); | |
drawLineSegment(g, order, p2, p3); | |
drawLineSegment(g, order, p3, p1); | |
} | |
private void drawLineSegment(Graphics g, int order, | |
Point startPoint, Point endPoint) { | |
if (order == 0) { | |
g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y); | |
} else { | |
Point distance = new Point((endPoint.x - startPoint.x) / 3, | |
(endPoint.y - startPoint.y) / 3); | |
Point p1 = new Point(startPoint.x + distance.x, | |
startPoint.y + distance.y); | |
Point p2 = new Point(p1.x + (int) (distance.x * 0.5 + | |
distance.y * Math.sin(Math.toRadians(-60))), | |
p1.y + (int) (distance.y * 0.5 - | |
distance.x * Math.sin(Math.toRadians(-60)))); | |
Point p3 = new Point(endPoint.x - distance.x, endPoint.y - distance.y); | |
drawLineSegment(g, order - 1, startPoint, p1); | |
drawLineSegment(g, order - 1, p1, p2); | |
drawLineSegment(g, order - 1, p2, p3); | |
drawLineSegment(g, order - 1, p3, endPoint); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment