Я должен реорганизовать ваш код следующим образом. Вы можете проверить случайное логическое выражение, чтобы рандомизировать создание компонента.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.swing.JComponent;
public class TetrisComponent extends JComponent{
private Map <String, Object> rectanglesIseries;
private Random randomGenerator;
public TetrisComponent() {
rectanglesIseries = new HashMap<>();
randomGenerator = new Random();
}
private void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
rectangleInitializer(g2,Color.black,Color.CYAN,new int[] {0, 100, 50, 50},"i");
rectangleInitializer(g2,Color.black,Color.CYAN,new int[] {50, 100, 50, 50},"i2");
rectangleInitializer(g2,Color.black,Color.CYAN,new int[] {100, 100, 50, 50},"i3");
rectangleInitializer(g2,Color.black,Color.CYAN,new int[] {150, 100, 50, 50},"i4");
}
private void paintComponentj(Graphics g){
Graphics2D g2 = (Graphics2D)g;
rectangleInitializer(g2,Color.black,Color.blue,new int[] {200, 500, 50, 50},"j");
rectangleInitializer(g2,Color.black,Color.blue,new int[] {250, 500, 50, 50},"j2");
rectangleInitializer(g2,Color.black,Color.blue,new int[] {300, 500, 50, 50},"j3");
rectangleInitializer(g2,Color.black,Color.blue,new int[] {300, 500, 50, 50},"j4");
}
private void rectangleInitializer(Graphics2D g2,Color drawColor,Color fillColor, int [] size, String element) {
rectanglesIseries.put(element, (Object)new Rectangle2D.Double());
g2.setColor(drawColor);
g2.draw((Rectangle2D.Double)rectanglesIseries.get(element));
g2.setColor(fillColor);
g2.fill((Rectangle2D.Double)rectanglesIseries.get(element));
}
public void randomComponentBuilder(Graphics g) {
if (randomGenerator.nextBoolean()) {
paintComponent(g);
} else {
paintComponentj(g);
}
}
}