import java.awt.*;
import javax.swing.*;
public class Fractal extends JFrame{
private PaintTriangle paintTriangle = new PaintTriangle();
public Fractal(){
paintFractal(1);
add(paintTriangle);
}
private void paintFractal(int n){
int p1X = getWidth() / 2;
int p1Y = 10;
int p2X = 10;
int p2Y = getHeight() - 10;
int p3X = getWidth() - 10;
int p3Y = getHeight() -10;
paintFractal(p1X, p1Y, p2X, p2Y, p3X, p3Y, n);
}
private void paintFractal(int p1X, int p1Y, int p2X, int p2Y, int p3X, int p3Y, int n){
if(n >= 0){
paintTriangle.paint(p1X, p1Y, p2X, p2Y, p3X, p3Y);
int p5X = (int)((p1X + p2X) / 2);
int p5Y = (int)((p1Y + p2Y) / 2);
int p4X = (int)((p3X + p2X) / 2);
int p4Y = (int)((p3Y + p2Y) / 2);
int p6X = (int)((p1X + p3X) / 2);
int p6Y = (int)((p1Y + p3Y) / 2);
paintFractal(p5X, p5Y, p2X, p2Y, p4X, p4Y, n - 1);
paintFractal(p6X, p6Y, p4X, p4Y, p3X, p3Y, n - 1);
paintFractal(p1X, p1Y, p5X, p5Y, p6X, p6Y, n - 1);
}
}
class PaintTriangle extends JPanel{
int p1X = 0;
int p1Y = 0;
int p2X = 0;
int p2Y = 0;
int p3X = 0;
int p3Y = 0;
public void paint(int p1X, int p1Y, int p2X, int p2Y, int p3X, int p3Y){
this.p1X = p1X;
this.p1Y = p1Y;
this.p2X = p2X;
this.p2Y = p2Y;
this.p3X = p3X;
this.p3Y = p3Y;
repaint();
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawLine(p1X, p1Y, p2X, p2Y);
g.drawLine(p1X, p1Y, p3X, p3Y);
g.drawLine(p3X, p3Y, p2X, p2Y);
}
}
public static void main(String[] args){
JFrame frame = new Fractal();
frame.setTitle("Fractal");
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}