In: Computer Science
please use java swing and recursion and the suggested method hints listed
Objective:
Write a program in which draws (yes it actually makes a picture) a triangular fractal using recursion. This is best if done using a java applet.
Suggested Methodology
The idea for it is this
First draw a filled equilateral triangle
Next draw another filled equilateral triangle of a different color that’s upside down in the middle of that triangle
Using the other triangles formed repeat step 2 until a pixel limit of 4 is reached
HINTS:
I
The method fillPolygon(int[] xPoints, int[] yPoint, numberOfPoints) as called by the graphics device is important
The method setColor(Color aColor) is important for picking different colors to draw things.
Example Image of Results:
please please thumbs up!!!
hope it will help uh out!!
Code::
(IN JAVA PROGRAMMING LANGUAGE)
--------------------------------------------------------
import java.awt.*;
import javax.swing.JApplet;
class Fractals extends JApplet {
private static final int SIZE = 400; // height/width of
applet
public void init() {
setPreferredSize(new Dimension(SIZE, SIZE)); // settin up
window
}
public void paint(Graphics g) {
super.paint(g);
// finding the coordinates of top center, bottom left and bottom
right
Point p1 = new Point(getWidth() / 2, 0);
Point p2 = new Point(0, getHeight());
Point p3 = new Point(getWidth(), getHeight());
// using white color
g.setColor(Color.WHITE);
// drawing a triangle with p1,p2,p3 as vertices
drawTriangle(p1, p2, p3, g);
// using black color
g.setColor(Color.BLACK);
// drawing fractals with n=half width
drawFractals(p1, p2, p3, g, getWidth() / 2);
}
public static void drawTriangle(Point p1, Point p2, Point p3,
Graphics g) {
// creating a polygon with the points and filling it
Polygon p = new Polygon();
p.addPoint(p1.x, p1.y);
p.addPoint(p2.x, p2.y);
p.addPoint(p3.x, p3.y);
g.fillPolygon(p);
}
public static void drawFractals(Point p1, Point p2, Point p3,
Graphics g,
int n) {
// checking if n reached the 4px limit
if (n <= 4) {
// base case: simple triangle
drawTriangle(p1, p2, p3, g);
} else {
// get the three middle points between p1 and p2, p1 and p3, p2
and
// p3
Point p4 = new Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);
Point p5 = new Point((p2.x + p3.x) / 2, (p2.y + p3.y) / 2);
Point p6 = new Point((p1.x + p3.x) / 2, (p1.y + p3.y) / 2);
// using recursive call to draw three sub-triangles, with
half
drawFractals(p1, p4, p6, g, n / 2);
drawFractals(p4, p2, p5, g, n / 2);
drawFractals(p6, p5, p3, g, n / 2);
}
}
}