I am starting to program in Java. We were instructed to execute some algorithms. I got the Sierpinski Triangle. I had the idea to create a 2D array and store the values, 0 = white rectangle, 1 = blue rectangle. I had big problems to do this (never had experience with swings / awt). I finally did this, but a strange visual error appeared at the end of the drawing. This is not the end, but the lines continue.
I have no idea why this is.
Here is my code:
Oknowhich extends JPanel:
package newpackage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Arrays;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class Okno extends JPanel {
public static int n = 500;
public static int[][] tabulka = new int[n][n];
public static void inicializaciaTabulky(){
for (int i = 0; i < n; i++) {
tabulka[0][i] = 1;
tabulka[i][0] = 1;
}
}
public static void doplnenieTabulky() {
for (int i = 1; i < n; i++) {
for (int j = 1; j < n; j++) {
if (tabulka[i-1][j] == 1 && tabulka[i][j-1] == 1 ||
tabulka[i-1][j] == 0 && tabulka[i][j-1] == 0) {
tabulka[i][j] = 0;
} else {
tabulka[i][j] = 1;
}
}
}
}
private void vykreslenie(Graphics g){
Graphics2D g2d = (Graphics2D) g;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
switch(tabulka[i][j]) {
case 0:
g.setColor(Color.white);
g.drawRect(i, j, 50, 50);
break;
case 1:
g.setColor(Color.blue);
g.drawRect(i, j, 50, 50);
break;
}
}
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
vykreslenie(g);
}
}
Trojuholnikwhich extends JFrame:
public class Trojuholnik extends JFrame {
public Trojuholnik() {
initUI();
}
private void initUI() {
setSize(800, 600);
setTitle("Sierpinski Triangle");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new Okno());
setLocationRelativeTo(rootPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Trojuholnik trojuholnik = new Trojuholnik();
trojuholnik.setVisible(true);
Okno.inicializaciaTabulky();
Okno.doplnenieTabulky();
System.out.println(Arrays.deepToString(Okno.tabulka));
}
});
}
}
The current result is as follows:

source
share