1

I have a java program that displays the Sierpinski Triangle. And each time you click the triangle in the applet it will add a triangle to each triangle. Is there a way I can bypass the mouseDown method and just hard code the triangle to display whatever number of iterations I want. Lets say I want the triangle to display the image as if I clicked it 5 times. How would I do this?

public class SierpinskiTriangle extends Applet {

//private static final long serialVersionUID = 1L;
Graphics g;

int deep = 0;

public void paint() {
    setBackground(new Color(255,255,255));
}

public boolean mouseDown(Event ev, int x, int y) {
    if (!ev.metaDown()) deep += 1;
    else if (deep>0) deep -= 1;
    repaint();
    return true;
}


public void paint(Graphics g) {
    // Create triangle
    int px[] = {20, 400, 210};
    int py[] = {400, 400, 20};

    g.setColor(Color.black);
    g.fillPolygon(px, py, 3);

    for(int i = 0; i < 5; i++)
    {
        paintTriangle(g, new Point(20,400),new Point(400,400),new Point(210,20), deep);
        i++;
    }
}

public void paintTriangle(Graphics g, Point a, Point b, Point c, int lvl) {

    Point a1,b1,c1, a2,b2,c2, a3,b3,c3;

    if (lvl==0) return;

    lvl = 3;

    // In the given triangle, amended to include an upside-down triangle
    int px[] = {c.x, (c.x+b.x)/2, (a.x+c.x)/2};
    int py[] = {b.y, (c.y+a.y)/2, (c.y+a.y)/2};

    g.setColor(Color.white);
    g.fillPolygon(px, py, 3);
    g.setColor(Color.red);
    g.drawPolygon(px, py, 3);

    // 3 new triangles 
    a1 = a;
    b1 = new Point(c.x, b.y);
    c1 = new Point((a.x+c.x)/2, (c.y+a.y)/2);
    paintTriangle(g, a1, b1, c1, lvl);

    a2 = new Point(c.x, b.y);
    b2 = b;
    c2 = new Point((c.x+b.x)/2, (c.y+a.y)/2);
    paintTriangle(g, a2, b2, c2, lvl);

    a3 = new Point((a.x+c.x)/2, (c.y+a.y)/2);
    b3 = new Point((c.x+b.x)/2, (c.y+a.y)/2);
    c3 = c;
    paintTriangle(g, a3, b3, c3, lvl);
  }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
developerME
  • 165
  • 1
  • 1
  • 7
  • 1) See [Java Plugin support deprecated](http://www.gizmodo.com.au/2016/01/rest-in-hell-java-plug-in/) and [Moving to a Plugin-Free Web](https://blogs.oracle.com/java-platform-group/entry/moving_to_a_plugin_free). 2) Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT components in favor of Swing. – Andrew Thompson Feb 12 '17 at 21:10

0 Answers0