What I should get in the end is a grid with squares that have stable colors if I resize the window. So far I get a grid that has random colors but as the everything is redrawn the colors are too. I'm thinking, maybe an array that stores the colors could work but I don't really know how to implement it in what I have so far.
public class GridRandomColors extends JFrame {
private static class Board extends JPanel {
private Rectangle MAIN_RECT;
private double BRICK_WIDTH, BRICK_HEIGHT;
private int COLS = 8;
private int ROWS = 8;
public Board() {
setBackground(Color.gray);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawRectangle(g);
drawBricks(g);
}
private void drawRectangle(Graphics g) {
if (getHeight() > getWidth()) {
MAIN_RECT = new Rectangle(0, 0, getWidth(), getWidth());
g.fillRect(0, (getHeight()-getWidth())/2, getWidth(), getWidth());
x = 0;
y = (getHeight()-getWidth())/2;
} else {
x = (getWidth()-getHeight())/2;
y = 0;
MAIN_RECT = new Rectangle(0, 0, getHeight(), getHeight());
g.fillRect((getWidth()-getHeight())/2, 0, getHeight(), getHeight());
}
BRICK_WIDTH = (float) MAIN_RECT.getWidth() / COLS;
BRICK_HEIGHT = (float) MAIN_RECT.getHeight() / ROWS ;
}
double spacing = 0.2;
private double x;
private double y;
private Color color;
private void drawBricks(Graphics g) {
Graphics2D brick = (Graphics2D) g.create();
for (int j = 0; j < ROWS; j++) {
for (int a = 0; a < COLS; a++) {
Random rand = new Random();
color = new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat());
Color oldColor = g.getColor();
brick.setColor(color);
Rectangle2D.Double rect = new Rectangle2D.Double(x, y, BRICK_WIDTH - spacing*(COLS-1), BRICK_HEIGHT- spacing*(ROWS-1));
brick.fill(rect);
brick.setColor(oldColor);
x += BRICK_HEIGHT+spacing;
}
if (getHeight() > getWidth()) {
x = 0;
}
else {
x = (getWidth() - getHeight()) / 2;
}
y += BRICK_HEIGHT+spacing;
}
}
}
public GridRandomColors() {
setDefaultCloseOperation(EXIT_ON_CLOSE); //mai bine cu exit on close
setSize(800, 820);
add(new Board());
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new GridRandomColors().setVisible(true);
}
});
}
}
Aucun commentaire:
Enregistrer un commentaire