How to use MouseListener to find a specific cell in a grid

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);
    }

// All Mouse Listener methods are in here.

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));
    }

    // Getter methods for x and y.

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

+5
3

, . , , Grid.

, Grid MouseListener, .

public class Grid extends JPanel {
    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++) {
                final Cell cell = new Cell(x, y);
                add(cell);
                cell.addMouseListener(new MouseListener() {
                    public void mouseClicked(MouseEvent e) {
                        click(e, cell);
                    }
                    // other mouse listener functions
                });
            }
        }        
    }

    public void click(MouseEvent e, Cell cell) {
        // handle the event, for instance
        cell.setBackground(Color.blue);
    }

    // handlers for the other mouse events
}

:

public class EnemyGrid extends Grid {
    public void click(MouseEvent e, Cell cell) {
        cell.setBackground(Color.red);
    }
}
+2
+2

The most obvious way is to move yours MouseListenerto the class Cell.

The second option I can think of is to use java.awt.Container.getComponentAt(int, int).

+1
source

All Articles