Hi, I need some help with some code. As of right now the program below prints the sierpinski triangle from the top left.

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

Hi, I need some help with some code. As of right now the program below prints the sierpinski triangle from the top left.

Post by answerhappygod »

Hi,
I need some help with some code. As of right now the program below
prints the sierpinski triangle from the top left. I need the top
point to be in the middle and the and the triangle to be centered
with the base at the bottom.
class Fractal1 {

public static void main(String[] args) {
int min = 9;


int max = 3;

int n = (int)Math.floor(Math.random()*(max-min+1)+min);

final int level = n;

JFrame frame = new
JFrame("Sierpinsky Triangle - Java");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel()
{

@Override
public
void paintComponent(Graphics g) {

g.setColor(Color.BLACK);

SierpinskyTriangle(level, 20, 20, 360,
(Graphics2D)g);
}
};

panel.setPreferredSize(new
Dimension(500, 500));

frame.add(panel);
frame.pack();

frame.setResizable(false);

frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

private static void SierpinskyTriangle(int
level, int x, int y, int size, Graphics2D g) {
if(level <= 0)
return;

g.drawLine(x, y, x+size,
y);
g.drawLine(x, y, x,
y+size);
g.drawLine(x+size, y, x,
y+size);

SierpinskyTriangle(level-1,
x, y, size/2, g);
SierpinskyTriangle(level-1,
x+size/2, y, size/2, g);
SierpinskyTriangle(level-1,
x, y+size/2, size/2, g);
}
}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply