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.
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.
My code for handling mouseclicked events:
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
if (pieceSelected == false)
{
pieceSelection = board[0][0];
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
jLabel1.setIcon(pieceSelection);
board[0][0] = 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;
//lastjPanel.setIcon(null)
pieceSelected = false;
}
}