I am currently trying to paint a grid with rectangles, but having some issues.
I am using an enum class for different type of SquareTypes
:
public enum SquareType
{
EMPTY, OUTSIDE, I, O, T, S, Z, J, L
}
These SquareTypes
are saved in arrays containing arrays in a Board
class. Then, paintComponent
-- which is supposed to draw my grid -- reaches in and get these object by using:
public SquareType getCell(int width, int height) {
return squares[width][height];
However, now when we get to paintComponent
:
public void paintComponent(Graphics g) {
super.paintComponent(g);
final Graphics2D g2d = (Graphics2D) g;
EnumMap<SquareType, Color> dictionary = new EnumMap<SquareType, Color>(SquareType.class);
dictionary.put(SquareType.EMPTY, Color.BLACK);
dictionary.put(SquareType.I, Color.LIGHT_GRAY);
dictionary.put(SquareType.J, Color.ORANGE);
dictionary.put(SquareType.L, Color.BLUE);
dictionary.put(SquareType.O, Color.YELLOW);
dictionary.put(SquareType.OUTSIDE, Color.BLUE);
dictionary.put(SquareType.S, Color.GREEN);
dictionary.put(SquareType.T, Color.CYAN);
dictionary.put(SquareType.Z, Color.RED);
for (int i = 0; i < game.getHeight(); i++) {
for (int j = 0; j < game.getWidth(); j++) {
g2d.setColor(dictionary.get(game.getCell(j,i)));
g2d.drawRect(0, 0, 52 * j, 52 * i);
}
}
}
}
The issue is that paintComponent
paints every square Blue, but if I use my getCell()
-method and check what is inside the actual cells I can clearly see that there are different SquareTypes
.
Might also add that the first rectangle which the the program draws is supposed to always be blue. So it seems to me as if it starts painting with blue and then sticks to it all the way? Why is that?
I am really new to the programming language and would love any help.
The line
g2d.drawRect(0, 0, 52 * j, 52 * i);
is clearly wrong. The method is described as follows:
drawRect(int x, int y, int width, int height)
So your line draws a rectangle above all prior drawn rectangles. Thats why your final result is a big blue rectangle.
I think it should be something like this:
g2d.drawRect(j * 52, i * 52, 52, 52);