Last active
June 17, 2022 09:25
-
-
Save itsamirhn/0ec38e82a3056715a93acd19d9c5e68e to your computer and use it in GitHub Desktop.
Draw Sierpinski iTriangle in GUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.swing.*; | |
import java.awt.*; | |
public class SierpinskiFrame extends JFrame { | |
public static void main(String[] args) { | |
SierpinskiFrame frame = new SierpinskiFrame(); | |
frame.setSize(600, 600); | |
frame.setLocationRelativeTo(null); | |
frame.setVisible(true); | |
} | |
SierpinskiPanel sierpinskiPanel = new SierpinskiPanel(); | |
JLabel label = new JLabel("N = " + sierpinskiPanel.getN()); | |
public SierpinskiFrame() { | |
super("Sierpinski Triangle"); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
JButton dw = new JButton("-"); | |
dw.addActionListener(e -> changeN(-1)); | |
JButton up = new JButton("+"); | |
up.addActionListener(e -> changeN(+1)); | |
JPanel buttonPanel = new JPanel(); | |
buttonPanel.add(dw); | |
buttonPanel.add(up); | |
add(buttonPanel, BorderLayout.SOUTH); | |
add(label, BorderLayout.NORTH); | |
add(sierpinskiPanel, BorderLayout.CENTER); | |
} | |
private void changeN(int d) { | |
sierpinskiPanel.setN(sierpinskiPanel.getN() + d); | |
label.setText("N = " + sierpinskiPanel.getN()); | |
} | |
static class SierpinskiPanel extends JPanel { | |
private int n = 1; | |
public int getN() { | |
return n; | |
} | |
public void setN(int n) { | |
if (n < 1) return; | |
this.n = n; | |
repaint(); | |
} | |
@Override | |
protected void paintComponent(Graphics g) { | |
super.paintComponent(g); | |
Point p1 = new Point(getWidth() / 2, 0); | |
Point p2 = new Point(0, getHeight()); | |
Point p3 = new Point(getWidth(), getHeight()); | |
drawTriangles(g, n, p1, p2, p3); | |
} | |
void drawTriangles(Graphics g, int order, Point p1, Point p2, Point p3) { | |
if (order == 1) { | |
g.drawLine(p1.x, p1.y, p2.x, p2.y); | |
g.drawLine(p2.x, p2.y, p3.x, p3.y); | |
g.drawLine(p3.x, p3.y, p1.x, p1.y); | |
} else { | |
Point p12 = new Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2); | |
Point p23 = new Point((p2.x + p3.x) / 2, (p2.y + p3.y) / 2); | |
Point p31 = new Point((p3.x + p1.x) / 2, (p3.y + p1.y) / 2); | |
drawTriangles(g, order - 1, p1, p12, p31); | |
drawTriangles(g, order - 1, p12, p2, p23); | |
drawTriangles(g, order - 1, p31, p23, p3); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment