Hi, I am a first Year Computer Science student learning java. First, what I want help with is not a homework assignment, I just started it on my own. This program is supposed to test the "Chaos Game" The chaos game is explained here: Chaos Game

So, the basics that I know I need to do are to find get a random point inside the triangle, connect it to a random vertex, find the midpoint, and then color in that dot. Some problems I had were filling in a single space, and for some reason, the line that I use instead of a dot is not being put inside the triangle. Here is my code.

/**
 * @(#)FractalStart.java
 *
 *
 * @author
 * @version 1.00 2007/11/15
 */

import javax.swing.JFrame;

public class FractalStart
{

    public static void main(String[] args)
    {
        JFrame frame = new JFrame ("Fractal");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        TriangleButton panel = new TriangleButton();

        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}



//Draws some triangles,
//Does some Fractal stuff with it.
//11-02-07

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();
    int point1 = gen.nextInt(300);
    int point2 = gen.nextInt(300);
    int side = 3;
    int point3;
    int point4;
    int midPoint1;
    int midPoint2;
    int point01;
    int point02;
    int[] dot1;
    int[] dot2;
    ArrayList<Integer> dots = new ArrayList<Integer>();  //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 void paintComponent (Graphics page)
    {
    	//This should be drawing each part dot through the loop
       super.paintComponent (page);
       page.setColor(Color.black);
       for (int count = 0; count < dots.size(); count++)
       {
			int Npoint = dots.get(count);
			count++;
			int Npoint1 = dots.get(count);
			int[] joe = {Npoint, Npoint1};
			int[] joe1 = {Npoint + 1, Npoint1 + 1};
			page.setColor(Color.red);
			page.drawPolyline(joe,joe1,joe.length);
       }
       page.setColor(Color.white);
       page.drawPolygon(triangle);
    }

    public void fractal1()
    {
    	//Makes two random points inside the triangle
    	//and then find the midpoint between that and a random side
    	do
    	{
    		point1 = gen.nextInt(500); //point inside triangle
    		point2 = gen.nextInt(500);

    		side = gen.nextInt(2);

    	}while (triangle.contains(point1,point2));


    	point3 = triangle01[side];  //x point
    	point4 = triangle02[side];  //y point of veritice

    	Integer midPoint1 = (point1 + point3) / 2;
    	Integer midPoint2 = (point2 + point4) / 2;

    	dots.add(midPoint1);  //adds the points to the dot.
    	dots.add(midPoint2);
    }



    private class DirectionListener implements KeyListener
    {
        public void keyPressed (KeyEvent event)
        {
            switch (event.getKeyCode())
            {
                case KeyEvent.VK_DOWN:
               		fractal1();
               		break;
            }
            repaint();
        }
        public void keyTyped (KeyEvent event) {}
        public void keyReleased (KeyEvent event) {}
    }
}

The problem is that the dots aren't being put inside the triangle, only on the right line of it.... Why is this? What's a good solution? I've been debugging for a while and it still escapes me what is going on.

Thank you for your help! Oh, and tell me anything that might make it better, but simple, cause this is my first year.

Recommended Answers

All 7 Replies

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.

Ummmm okay, I'm going to state my problem again, cause My problem still isn't fixed...... Alright, so I thought I was doing everything correct, and it looks like it should be coming But, for some reason, the points that are made are not appearing inside the triangle, instead they make a line along the edge of the triangle! I put my problem in Italics, it would be great if someone could tell me why this is happening!

Member Avatar for iamthwee

which one are you trying to do the Sierpinski Triangle?

Ummmm okay, I'm going to state my problem again, cause My problem still isn't fixed...... Alright, so I thought I was doing everything correct, and it looks like it should be coming But, for some reason, the points that are made are not appearing inside the triangle, instead they make a line along the edge of the triangle! I put my problem in Italics, it would be great if someone could tell me why this is happening!

Well, for one thing, you were not calculating the inner point correctly. The code that I reworked a bit for you does give a random inside point, without some of the hassles you were having with the data structures. Since I already took the time to get that working for you, I'm not much inclined to fiddle any more with it. By the way - you're welcome.

edit:

Oh, and tell me anything that might make it better, but simple

Which I did...

Well, for one thing, you were not calculating the inner point correctly. The code that I reworked a bit for you does give a random inside point, without some of the hassles you were having with the data structures. Since I already took the time to get that working for you, I'm not much inclined to fiddle any more with it. By the way - you're welcome.

edit: Which I did...

Sorry, I didn't mean that I didn't appreciate your help that you gave me. Thank you!

But, I just got a bit irritated, because It's still the same problem that illudes me completely of why it's not working....

One last time: Thank You again, and does anyone have any clue why they aren't going inside the triangle?

BTW, yes, I'm starting with the Triangle....

:-O It's working now! I..... don't get it! It wasn't working before! That is crazy.... THANK YOU Ezzaral !!!! Man, now I feel bad for saying that you didn't solve my problem, cause you did, I think.... I willl probably add those functionallity that you said pretty soon, I'll post them when I get them done.

alright, I've pretty much got the whole thing done, just some touch up that I might not ever do. Oh, and we haven't gone over exceptions, so that's why there are'nt any in there.

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 Fractal2 extends JPanel
{
    private int[] triangle01 = {10, 500, 245};
    private int[] triangle02 = {10, 10, 440};
    private int[] square01 = {10,500,500,10};
    private int[] square02 = {10,10,500,500};

    Random gen = new Random();

    ArrayList<Point> dots = new ArrayList<Point>();  //holds all the points that 
    //are made in this program
    
    ArrayList<Point> newShape = new ArrayList<Point>(); // Holds the points
    //for the new user entered shape

    Polygon triangle = new Polygon(triangle01, triangle02, triangle01.length);
    Polygon square = new Polygon(square01, square02, square01.length);
    Point previousPoint = getInnerPoint(triangle);
    Polygon currentPolygon = triangle;
    JRadioButton square1, triangle1, user;
    JButton add1, add10, add100, add1000;
    JButton clear;
    int currentnum = 1;
    int currentden = 2;
    JTextField den, num;
    Polygon userShape;
	

	public Fractal2 ()
	{
		setLayout(new BorderLayout());
    	JPanel south = new JPanel();


    	JLabel numerator = new JLabel("numerator");
    	JLabel denominator = new JLabel("denominator");
    	den = new JTextField("2", 3);
    	num = new JTextField("1", 3);

    	square1 = new JRadioButton("Square ", false);
    	triangle1 = new JRadioButton("Triangle", true);
    	user = new JRadioButton("User", false);

    	ButtonGroup group = new ButtonGroup();
    	group.add(triangle1);
    	group.add(square1);
    	group.add(user);

    	ShapeListener listener = new ShapeListener();
    	square1.addActionListener(listener);
    	triangle1.addActionListener(listener);

    	add1 = new JButton ("1");
    	add10 = new JButton ("10");
    	add100 = new JButton ("100");
    	add1000 = new JButton ("1000");
    	clear = new JButton ("Clear");
    	add1.addActionListener(listener);
    	add10.addActionListener(listener);
    	add100.addActionListener(listener);
    	add1000.addActionListener(listener);
    	clear.addActionListener(listener);

		south.add(add1);
		south.add(add10);
		south.add(add100);
		south.add(add1000);
		south.add(triangle1);
		south.add(square1);
		south.add(clear);
		south.add(numerator);
		south.add(num);
		south.add(denominator);
		south.add(den);
		south.add(clear);
		
		


		add(south, BorderLayout.SOUTH);
		NewShapeListener listener2 = new NewShapeListener();
		addMouseListener (listener2);
		addMouseMotionListener (listener2);

    	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);

        Fractal2 panel = new Fractal2();

        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.white);
        for (Point p : dots){
            g2d.fillRect(p.x,p.y,1,1);
        }
        g2d.setColor(Color.white);
        g2d.drawPolygon(currentPolygon);
            }


    public void createFractalPoint(Polygon poly){
        Point vertex = getVertex(poly);
        if (dots.size() == 0)
        {
        	dots.add(previousPoint);
        }
        Point last = dots.get(0);
        for (Point x : dots)
        	last = x;
        Point inner = getDistance(last, vertex, currentnum, currentden);
        dots.add(inner);
    }

    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 getDistance(Point p1, Point p2, int numerator, double denom) {
        return new Point((int)( ((p1.x+p2.x) * numerator) / denom), (int)( (
        	(p1.y+p2.y) * numerator) / denom));      }
    
    public Polygon getUserShape()
    {
    	int size = newShape.size();
    	int[] userShapex = new int[size];
    	for (int x = 0; x < size; x++)
    	{
    		userShapex[x] = newShape.get(x).x;
    	}
    	int[] userShapey = new int[size];
    	for (int x = 0; x < size; x++)
    	{
    		userShapey[x] = newShape.get(x).y;
    	}
    	Polygon userShape = new Polygon(userShapex, userShapey, size);
    	return userShape;

    	
    }

    private class ShapeListener implements ActionListener
    {
    	public void actionPerformed (ActionEvent event)
    	{
    		Object source = event.getSource();
    		String denValStr = den.getText();
    		String numValStr = num.getText();
    		currentnum = Integer.parseInt(numValStr);
    		currentden = Integer.parseInt(denValStr);

    		if (source == square1)
    		{
    			dots.clear();
    			currentPolygon = square;
    		}
    		else if (source == triangle1)
    		{
    			dots.clear();
    			currentPolygon = triangle;
    		}
    		repaint();
    		if (source == add1)
    			createFractalPoint(currentPolygon);
    		else if (source == add10)
    		{
    			int x = 0;
    			while (x < 10)
    			{

    				createFractalPoint(currentPolygon);
    				x++;
    			}
    		}
    		else if (source == add100)
    		{
    			int x = 0;
    			while (x < 100)
    			{
    				createFractalPoint(currentPolygon);
    				x++;
    			}

    		}
    		else if (source == add1000)
    		{
    			int x = 0;
    			while ( x < 1000)
    			{
    				createFractalPoint(currentPolygon);
    				x++;
    			}
    		}
    		else if (source == clear)
    		{
    			newShape.clear();
    		}
    		else if (source == user)
    		{
    			if (newShape.size() > 2)
    				userShape = getUserShape(); 
    		}
    		repaint();
    	}
    }
    
    private class NewShapeListener implements MouseListener, MouseMotionListener
    {
    	public void mousePressed (MouseEvent event)
    	{
    		Point point1 = event.getPoint();
    		newShape.add(point1);
    		if (newShape.size() > 2)
    			currentPolygon = getUserShape();
    		repaint();
    	}
    	public void mouseClicked (MouseEvent event) {}
    	public void mouseReleased (MouseEvent event) {}
    	public void mouseEntered (MouseEvent event) {}
    	public void mouseExited (MouseEvent event) {}
    	public void mouseMoved (MouseEvent event) {}
    	public void mouseDragged (MouseEvent event) {}
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.