Try this as a starting point
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.util.ArrayList;
public class Fractal extends JPanel
{
private int[] triangle01 = {150, 300, 150};
private int[] triangle02 = {300, 300, 150};
Random gen = new Random();
ArrayList<Point> dots = new ArrayList<Point>(); //holds all the points that are made in this program
Polygon triangle = new Polygon(triangle01, triangle02, triangle01.length);
public Fractal ()
{
addKeyListener (new DirectionListener());
setFocusable(true);
setBackground (Color.black);
setPreferredSize (new Dimension (1000,1000));
}
public static void main(String[] args)
{
JFrame frame = new JFrame ("Fractal");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Fractal panel = new Fractal();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
public void paintComponent (Graphics page)
{
Graphics2D g2d = (Graphics2D)page;
g2d.setBackground(Color.black);
g2d.clearRect(0,0,getWidth(), getHeight());
g2d.setColor(Color.red);
for (Point p : dots){
g2d.fillRect(p.x,p.y,1,1);
}
g2d.setColor(Color.white);
g2d.drawPolygon(triangle);
}
public void createFractalPoint(Polygon poly){
Point inner = getInnerPoint(poly);
Point vertex = getVertex(poly);
dots.add( getMidpoint(inner, vertex) );
}
public Point getInnerPoint(Polygon poly){
Rectangle2D bounds = poly.getBounds2D();
Point p;
do {
p = new Point((int)(bounds.getMinX() + gen.nextFloat()*bounds.getWidth()),(int)(bounds.getMinY() + gen.nextFloat()*bounds.getHeight()));
} while (!poly.contains(p));
return p;
}
public Point getVertex(Polygon poly){
int index = gen.nextInt(poly.npoints);
return new Point(poly.xpoints[index], poly.ypoints[index]);
}
public Point getMidpoint(Point p1, Point p2) {
return new Point((int)((p1.x+p2.x)/2), (int)((p1.y+p2.y)/2));
}
private class DirectionListener implements KeyListener
{
public void keyPressed (KeyEvent event)
{
createFractalPoint(triangle);
repaint();
}
public void keyTyped (KeyEvent event) {}
public void keyReleased (KeyEvent event) {}
}
} This still gives you some room to grow on. You are just using the midpoint, but the algorithm calls for a random distance between the point and vertex. You can easily do that with the slope and distance between the point and vertex.
You might also consider a method that takes a number of sides and creates that polygon for use, instead of the statically defined triangle that is there currently.
Hope this helps a bit.
Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847