0

Im building a board using GUI(may be board game). I have created 2D array to make cells like Gomoku game. I want to make this function: Whenever i click a cell, the cell position will be displayed.

private Cell[][] cells;
private in row;
private int col;

Update:
.......

JPanel pn = new JPanel(new GridLayout(row, col, 0, 0));
cells = new Cell[row][col];
for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            pn.add(cells[i][j] = new Cell());
        }
......
private class MouseListener extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
                    for (int i = 0; i < size; i++) {
                        for (int j = 0; j < size; j++) {
                            if (         ) {
                                System.out.println("X: " + i + ", Y: " + j);

                            }

                        }
                    }
            }

I cant make it work although i've tried several times and different conditions in if

Raku Ichijo
  • 1
  • 1
  • 3

3 Answers3

1

You can add your MouseListener directly to the cells and use e.getSource() to get clicked cell.

StanislavL
  • 56,971
  • 9
  • 68
  • 98
0

There should be a hit test function call in your if statement. The hit test function should translate from mouse coordinates to Cell coordinates for the current (i,j) position, and return a simple true or false. (And as soon as you get a true, you can exit both loops.)

You don't show how you are drawing the grid, though. If your grid starts at a position (xp,yp) and every cell has a height h and width w, you can easily convert mouse coordinates directly into cell coordinates:

cellx = (mousex - xp)/w
celly = (mousey - yp)/h

... where a cellx,celly < 0 or >= size would indicate a click outside the grid.

Jongware
  • 22,200
  • 8
  • 54
  • 100
0

Without knowing much about what is on the screen we can apply the following. As long as there is no offset from the edge of the canvas to where you rendered the cells you can use the follow, if there is offset, you will need to add it to the x,y coordinates.

int x = 201;  //You would use e.getX();
int y = 10;   //You would use e.getY();

int xWidth = 50;
int yWidth = 50;

//Divide by the width to get the array position
int xIndex = (int)Math.floor(x / xWidth);
int yIndex = (int)Math.floor(y / yWidth);
verbanicm
  • 2,406
  • 1
  • 14
  • 9