1 | initial version |
Yes, the Sierpinski triangle can be created recursively using Java. Here is an example code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SierpinskiTriangle extends JFrame {
private int order = 0; // Initial order of Sierpinski triangle
public SierpinskiTriangle() {
setLayout(new BorderLayout());
add(new TrianglePanel(order)); // Add TrianglePanel to JFrame
}
// Define TrianglePanel
static class TrianglePanel extends JPanel {
private int order; // Order of current Sierpinski triangle
public TrianglePanel(int order) {
this.order = order;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Define triangle vertices
int x1 = getWidth() / 2;
int y1 = 10;
int x2 = 10;
int y2 = getHeight() - 10;
int x3 = getWidth() - 10;
int y3 = getHeight() - 10;
// Draw Sierpinski triangle recursively
displayTriangles(g, order, x1, y1, x2, y2, x3, y3);
}
// Draw Sierpinski triangle recursively
private void displayTriangles(Graphics g, int order,
int x1, int y1, int x2, int y2, int x3, int y3) {
if (order == 0) {
// Base case: draw triangle
g.drawLine(x1, y1, x2, y2);
g.drawLine(x1, y1, x3, y3);
g.drawLine(x2, y2, x3, y3);
} else {
// Recursive case: draw smaller triangles
int x12 = (x1 + x2) / 2;
int y12 = (y1 + y2) / 2;
int x23 = (x2 + x3) / 2;
int y23 = (y2 + y3) / 2;
int x31 = (x3 + x1) / 2;
int y31 = (y3 + y1) / 2;
displayTriangles(g, order - 1, x1, y1, x12, y12, x31, y31);
displayTriangles(g, order - 1, x12, y12, x2, y2, x23, y23);
displayTriangles(g, order - 1, x31, y31, x23, y23, x3, y3);
}
}
}
public static void main(String[] args) {
JFrame frame = new SierpinskiTriangle();
frame.setTitle("Sierpinski Triangle");
frame.setSize(400, 400);
frame.setLocationRelativeTo(null); // Center frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
This code defines a TrianglePanel
class that extends JPanel
and draws a Sierpinski triangle recursively using the displayTriangles
method. The SierpinskiTriangle
class is a JFrame
that contains a TrianglePanel
and sets the initial order of the Sierpinski triangle to 0. The main
method creates an instance of SierpinskiTriangle
, sets the title, size, and location of the JFrame, and makes it visible.