I am trying to create a Java game with a 10 x 10 grid consisting of cells. The grid is as follows:
public class Grid extends JPanel implements MouseListener {
public static final int GRID_SIZE = 10;
public Grid() {
setPreferredSize(new Dimension(300, 300));
setLayout(new GridLayout(GRID_SIZE, GRID_SIZE));
for (int x = 0; x < GRID_SIZE; x++)
for (int y = 0; y < GRID_SIZE; y++)
add(new Cell(x, y));
addMouseListener(this);
}
The Cell class is as follows:
public class Cell extends JPanel {
public static final int CELL_SIZE = 1;
private int xPos;
private int yPos;
public Cell (int x, int y) {
xPos = x;
yPos = y;
setOpaque(true);
setBorder(BorderFactory.createBevelBorder(CELL_SIZE));
setBackground(new Color(105, 120, 105));
setPreferredSize(new Dimension(CELL_SIZE, CELL_SIZE));
}
My problem is that now I'm trying to implement MouseListeners in a Grid class. I realized that although I can return the X and Y coordinates of the grid, I cannot manipulate the cells themselves. I guess this is because when I created them in the Grid, I create 100 random cells without identifiers, and therefore I have no way to access them directly.
Can anyone give me some advice on this? Do I need to review my code and the way cells are created? Am I terribly stupid and don't see obvious access to them? Thanks