0

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; 
    } 
}
Michael
  • 57,169
  • 9
  • 80
  • 125
  • See also this [example](http://stackoverflow.com/a/2562685/230513) and [variation](http://stackoverflow.com/a/2563350/230513). – trashgod Jun 14 '13 at 15:52

1 Answers1

0

You should make a two dimensional array of size [8][8] of jPanels, e.g.

JPanel[8][8] chessBoard = ...

rather than having

JPanel jPanel1...
JPanel jPanel2...
JPanel jPanel3...
JPanel jPanel4...
...

Then you can access all JPanels in the same way, programmatically, without needing to write any piece of code out 64 times. You can iterate, search, etc, whatever.

Patashu
  • 21,443
  • 3
  • 45
  • 53