Hello I'm trying to make a chess game, so far I have created my pieces and I can move them with my mouse.
Now I'm trying to make the board with a 2D array that contains chess piece, so that I when I drag a piece on the board, it adds the piece in the array for example on the image I drag the piece to (2,3) and board = pawn
But I'm not sure how to implement it, I thought about using coordinates like when I drag it into the middle , say I have a frame size of 800x800 and board size of 8 so when I drag my piece to the coordinate (400,400), board = pawn but then I have to do it for each cell and i'm gonna end up with up 64 if conditions, is there some kind of trick to do it or is my approach wrong ?
There are lots of ways to do that sort of thing. This is one idea. Other people will doubtless have different suggestions.
Consider changing the board to comprise an 8×8 grid of 64 buttons. Set all buttons with pieces on to “source” mode. Click on one source button, and turn all the other 63 buttons to “destination” mode. Click on a button and move your piece to that button. Then the buttons with pieces on can revert to source mode.
Needless to say, ,that is a dreadful oversimplification of the procedure.
I agree with Campbell. An easy method is to use JLabels (each jlabel the size of a square), with an image of the chess piece as icon (or no icon if the corresponding square is empty). Add a MouseListener to all the Labels. If a JLabel is clicked, register the label as "from", and the next click on a JLabel will indicate the "to" field. If the "move" is legal, then delete the icon of the "from" label, and set it as icon of the "to" label.
It would be easy to create a class that extends JLabel., with additional fields 'row' and 'column'. If the MouseListener is invoked after a mouse click, you ask for the source of the click, and then you know at once which Label has been clicked.
It is also pretty easy to drag the piece to its new location, but that is another story.