I am trying to create a human on human chess program using java swing. I have 64 jPanels back to back (alternating between grey and white background colors), with a jLabel inside each one that I am using to display icons for the pieces. Right now I'm trying to make it so that you can move a piece from one panel to another by clicking the panels in sucession. I also am using an icon array called "board" to store the positions of all the pieces. Right now, I have the following code for the mouseclicked event for each jPanel. So far the program sucesfully duplicates the icon of the first clicked jPanel to the second (and makes the corresponding change to the board array). However, I am having trouble removing the icon from the first clicked jPanel so that the piece actually 'moves', rather than just duplicating. I know I somehow need to store which panel is originally selected in some kind of variable, and then use that variable to set the icon of the original jPanel to null when the second panel is clicked. However, short of using an integer for the selected panel (1-64), and then a really long switch statement (switch (int), case 1: jPanel1.setIcon(null), case 2: jPanel2.setIcon(null)), etc.), I don't know what kind of variable to use. Is there an easier way to do this (than just using the switch statement)? Like some kind of object variable that I can store a swing object inside and then use later to command whatever object is stored inside? Anyone know how to do what I'm talking about? Help would be much appreciated.
if (pieceSelected == false)
pieceSelection = board;
pieceSelected = true;
} else //if a piece was selected when this panel was clicked
//change this panel's icon to the icon of the first panel
board = pieceSelection;
//change the icon of the first square clicked to null
//the following part is the part i'm having trouble with
//board[last x coordinate][last y coordinate] = null;
yes, there are better ways to do it. I'll show you the gui that I use for my chessboard. Note however, there are "many roads leading to Rome",
so don't think my way is the only possible way.
first of all, I only use one JPanel for the chessboard; let's call it jp_Chessoard. And I use a GridLayout(8,8) as the LayoutManager.
In the grid, I will put JLabels, albeit it special ones. Here is my ChessSquare (in Dutch: Bordveld):
And then I do the following routine:
And lastly, I have an array of integers, 8 by 8, that represents the chess position; each piece having a certain fixed value.
And from this array I decide what icon to put in my Bordveld labels. Don't forget to put the jp_Chessborad to a JFrame.
Well, I hope that with the code given you have some idea of how to get a chessboard on your screen, with some fairly short code.