Mukarram Mukhtar

Chess Board in JAVA

As explained in the introduction section of this tutorial, the code posted in this article will only help you drawing a chess board, placing pieces at the proper positions and making moves of the pieces. If you are interested in more advanced features then this article might not be able to help you. In order to run the following code you need JVM (Java Virtual Machine) running on your computer. Java can be downloaded and installed from the following website:

http://www.oracle.com/technetwork/java/javaee/overview/index.html

Before I post the code, let me show you the screenshots of the application after it is built:


After you compile and run the application, the window shown above will be displayed. Since white pieces are arranged in the bottom section, it means you’ve been assigned white color. Now you can select any piece and piece will turn gray as shown in the following screenshot:


After selecting your piece you can move it anywhere in the board. As shown in the following screenshot:


Actually right now, since move validity is not being checked, you can even take your own piece even. But let’s not do it for now. Alright folks, that’s all for today, enjoy the following code and if you need, ask me for the whole project, ciao…

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class frmChessBoard extends JFrame implements MouseListener

{    

      public static void main(String[] args)

      {

            final frmChessBoard app = new frmChessBoard();             

      }

      // the whole constructor is for setting up the UI of the form

      public frmChessBoard()

      {

            c = getContentPane();

            setBounds(100, 100, 470, 495);

            setBackground(new Color(204, 204, 204));

            setDefaultCloseOperation(EXIT_ON_CLOSE);

            setTitle("Tutorial: How to Draw a Chess Board in Java");

            setResizable(false);

            c.setLayout(null);     

            pnlMain.setBounds(3, 3, 460, 460);

            pnlMain.setBackground(new Color(255, 255, 255));

            c.add(pnlMain);

            this.drawChessBoard();

            this.arrangeChessPieces();

            show();

      }

      // This method captures the move on the chess board and then make

      // it happen, logically and physically; also, it sends the move to

      // the other client

      public void mouseClicked(MouseEvent e)

      {

            if(bMyTurn)

            {                

                  Object source = e.getSource();

                  JPanel pnlTemp = (JPanel)source;         

                  int intX = (pnlTemp.getX()/57);

                  int intY = (pnlTemp.getY()/57);

                  this.boolMoveSelection = !this.boolMoveSelection;

                  if(this.boolMoveSelection)

                  {

                        this.pntMoveFrom = new Point(intX, intY);

                        if(this.strChessBoard[this.pntMoveFrom.y][this.pntMoveFrom.x].toString().trim().equals(""))

                              this.boolMoveSelection = !this.boolMoveSelection;

                        if((!this.strChessBoard[this.pntMoveFrom.y][this.pntMoveFrom.x].toString().trim().equals("")) &&

                                    this.bWhite && this.strChessBoard[this.pntMoveFrom.y][this.pntMoveFrom.x].toString().charAt(1) == 'B')

                              this.boolMoveSelection = !this.boolMoveSelection;

                        if((!this.strChessBoard[this.pntMoveFrom.y][this.pntMoveFrom.x].toString().trim().equals("")) &&

                                    !this.bWhite && this.strChessBoard[this.pntMoveFrom.y][this.pntMoveFrom.x].toString().charAt(1) == 'W')

                              this.boolMoveSelection = !this.boolMoveSelection;

                        if(this.boolMoveSelection)

                              this.makeChessPieceDifferent(true);

                  }

                  else

                  {

                        this.pntMoveTo = new Point(intX, intY);

                        if(!this.pntMoveFrom.equals(this.pntMoveTo))

                        {

                              if(      this.strChessBoard[this.pntMoveFrom.y][this.pntMoveFrom.x].toString().trim() != "")

                                    if(this.isMoveValid())

                                    {                                        

                                          this.strChessBoard[this.pntMoveTo.y][this.pntMoveTo.x] = this.strChessBoard[this.pntMoveFrom.y][this.pntMoveFrom.x].toString();

                                          this.strChessBoard[this.pntMoveFrom.y][this.pntMoveFrom.x] = "  ";

                                          this.moveChessPiece();                                     

                                    }

                                    else

                                    {

                                          JOptionPane.showMessageDialog(this, "Invalid Move Request.", "Warning", JOptionPane.ERROR_MESSAGE);

                                          this.makeChessPieceDifferent(false);

                                    }

                        }

                        else

                              this.makeChessPieceDifferent(false);

                  }    

            }

      }    

      // This method checks if attempted move is valid or not

      private boolean isMoveValid()

      {

            boolean isMoveValid = true;

            return isMoveValid;

      }

      // This method makes the selected chess piece looks like selected

      private void makeChessPieceDifferent(boolean bSelected)

      {

      for(int z = 0; z < this.pnlChessCells[this.pntMoveFrom.y][this.pntMoveFrom.x].getComponentCount(); z++)

            if(this.pnlChessCells[this.pntMoveFrom.y][this.pntMoveFrom.x].getComponent(z).getClass().toString().indexOf("JLabel") > -1)

            {

                  JLabel lblTemp = (JLabel)this.pnlChessCells[this.pntMoveFrom.y][this.pntMoveFrom.x].getComponent(z);

                  lblTemp.setEnabled(!bSelected);

            }          

      }

      // If class level variables Point-From and Point-To are set,

      // then this method actually moves a piece, if any exists, from

      // one cell to the other

      private void moveChessPiece()

      {

      for(int z = 0; z < this.pnlChessCells[this.pntMoveTo.y][this.pntMoveTo.x].getComponentCount(); z++)

            if(this.pnlChessCells[this.pntMoveTo.y][this.pntMoveTo.x].getComponent(z).getClass().toString().indexOf("JLabel") > -1)

            {

                  this.pnlChessCells[this.pntMoveTo.y][this.pntMoveTo.x].remove(z);

                  this.pnlChessCells[this.pntMoveTo.y][this.pntMoveTo.x].repaint();

            }

      for(int z = 0; z < this.pnlChessCells[this.pntMoveFrom.y][this.pntMoveFrom.x].getComponentCount(); z++)

            if(this.pnlChessCells[this.pntMoveFrom.y][this.pntMoveFrom.x].getComponent(z).getClass().toString().indexOf("JLabel") > -1)

            {

                  this.pnlChessCells[this.pntMoveFrom.y][this.pntMoveFrom.x].remove(z);

                  this.pnlChessCells[this.pntMoveFrom.y][this.pntMoveFrom.x].repaint();

            }

          this.pnlChessCells[this.pntMoveTo.y][this.pntMoveTo.x].add(this.getPieceObject(this.strChessBoard[this.pntMoveTo.y][this.pntMoveTo.x]), BorderLayout.CENTER);

      this.pnlChessCells[this.pntMoveTo.y][this.pntMoveTo.x].validate();

      }

      // Given the code of a piece as a string, this method instantiates

      // a label object with the right image inside it

      private JLabel getPieceObject(String strPieceName)

      {

            JLabel lblTemp;

      if(strPieceName.equals("RB"))

            lblTemp = new JLabel(this.rookBlack);

      else if(strPieceName.equals("BB"))

            lblTemp = new JLabel(this.bishopBlack);

      else if(strPieceName.equals("NB"))

            lblTemp = new JLabel(this.knightBlack);

      else if(strPieceName.equals("QB"))

            lblTemp = new JLabel(this.queenBlack);

      else if(strPieceName.equals("KB"))

            lblTemp = new JLabel(this.kingBlack);

      else if(strPieceName.equals("PB"))

            lblTemp = new JLabel(this.pawnBlack);

      else if(strPieceName.equals("RW"))

            lblTemp = new JLabel(this.rookWhite);

      else if(strPieceName.equals("BW"))

            lblTemp =  new JLabel(this.bishopWhite);

      else if(strPieceName.equals("NW"))

            lblTemp = new JLabel(this.knightWhite);

      else if(strPieceName.equals("QW"))

            lblTemp = new JLabel(this.queenWhite);

      else if(strPieceName.equals("KW"))

            lblTemp = new JLabel(this.kingWhite);

      else if(strPieceName.equals("PW"))

            lblTemp = new JLabel(this.pawnWhite);

      else

            lblTemp = new JLabel();

            return lblTemp;

      }

      // This method reads strChessBoard two-dimensional array of string

      // and places chess pieces at their right positions

      private void arrangeChessPieces()

      {                      

            for(int y = 0; y < 8; y++)       

            for(int x = 0; x < 8; x++) 

            {                

                  this.pnlChessCells[y][x].add(this.getPieceObject(strChessBoard[y][x]), BorderLayout.CENTER);

                  this.pnlChessCells[y][x].validate();

            }          

      }

      // This method draws chess board, i.e. black and white cells on the board

      private void drawChessBoard()

      {

            for (int y = 0; y < 8; y++)

                  for (int x = 0; x < 8; x++)

                  {

                        pnlChessCells[y][x] = new JPanel(new BorderLayout());

                        pnlChessCells[y][x].addMouseListener(this);

                        pnlMain.add(pnlChessCells[y][x]);

                        if (y % 2 == 0)

                              if (x % 2 != 0)

                                    pnlChessCells[y][x].setBackground(Color.DARK_GRAY);

                              else

                                    pnlChessCells[y][x].setBackground(Color.WHITE);

                        else

                              if (x % 2 == 0)

                                    pnlChessCells[y][x].setBackground(Color.DARK_GRAY);

                              else

                                    pnlChessCells[y][x].setBackground(Color.WHITE);

                  }

      }

      public void mouseEntered(MouseEvent e){} 

      public void mouseReleased(MouseEvent e){}

      public void mouseExited(MouseEvent e){}  

      public void mousePressed(MouseEvent e){}

      private JPanel[][] pnlChessCells = new JPanel[8][8];

      private JPanel pnlMain = new JPanel(new GridLayout(8,8));

      private String[][] strChessBoard = new String[][] { {"RB", "NB", "BB", "QB", "KB", "BB", "NB", "RB" }, {"PB", "PB", "PB", "PB", "PB", "PB", "PB", "PB"}, {"  ", "  ", "  ", "  ", "  ", "  ", "  ", "  "}, {"  ", "  ", "  ", "  ", "  ", "  ", "  ", "  "}, {"  ", "  ", "  ", "  ", "  ", "  ", "  ", "  "}, {"  ", "  ", "  ", "  ", "  ", "  ", "  ", "  "}, {"PW", "PW", "PW", "PW", "PW", "PW", "PW", "PW"}, {"RW", "NW", "BW", "QW", "KW", "BW", "NW", "RW"} };

      private ImageIcon rookBlack = new ImageIcon(System.getProperty("user.dir") + "/images/RookBlack.png");

      private ImageIcon rookWhite = new ImageIcon(System.getProperty("user.dir") + "/images/RookWhite.png");

      private ImageIcon bishopBlack = new ImageIcon(System.getProperty("user.dir") + "/images/BishopBlack.png");

      private ImageIcon bishopWhite = new ImageIcon(System.getProperty("user.dir") + "/images/BishopWhite.png");

      private ImageIcon knightBlack = new ImageIcon(System.getProperty("user.dir") + "/images/KnightBlack.png");

      private ImageIcon knightWhite = new ImageIcon(System.getProperty("user.dir") + "/images/KnightWhite.png");

      private ImageIcon kingBlack = new ImageIcon(System.getProperty("user.dir") + "/images/KingBlack.png");

      private ImageIcon kingWhite = new ImageIcon(System.getProperty("user.dir") + "/images/KingWhite.png");

      private ImageIcon queenBlack = new ImageIcon(System.getProperty("user.dir") + "/images/QueenBlack.png");

      private ImageIcon queenWhite = new ImageIcon(System.getProperty("user.dir") + "/images/QueenWhite.png");

      private ImageIcon pawnBlack = new ImageIcon(System.getProperty("user.dir") + "/images/PawnBlack.png");

      private ImageIcon pawnWhite = new ImageIcon(System.getProperty("user.dir") + "/images/PawnWhite.png");

      private boolean boolMoveSelection = false, bWhite = true, bMyTurn = true;

      private Point pntMoveFrom, pntMoveTo;

      private Container c;

}

51 Comments »

  1. Hi Mukarram, I like the looks of your chessboard but I can only replicate the board itself as I don’t have access to the icons for the different pieces. Is it possible to send these to me through email please?

    Thanks,
    Luc

    Comment by Luc — December 2, 2010 @ 9:13 am

    • Sure Luc, e-mail is on its way.

      Your e-mail address looked little different to me, so if you fail to receive my e-mail, then don’t hesitate letting me know and I’ll resend it.

      Enjoy! 🙂

      Comment by Mukarram Mukhtar — December 6, 2010 @ 4:00 pm

      • can you give the whole program to my email acc. just send to “rockman_200316@yahoo.com” thank you

        Comment by yves — December 28, 2011 @ 4:45 am

      • can you send me the same at sagarsurendragupta22@gmail.com thank you 🙂

        Comment by SAGAR — June 2, 2013 @ 5:10 pm

  2. Good day Mukarram,i really appreciate your post but i need a favour from you i have similar project but mine is on processing may be you have heard of it it uses java syntax could you help me with the code of creating the board nd how to validate each piece.you would be a life saver

    Comment by Rabiu Ademoh — December 5, 2010 @ 2:01 pm

    • Hi Rabiu, as much as I would love to help you, it is really very hard for me to provide solutions for everybody over the internet. If you please explain further on what exactly your project requirements are then perhaps I would be able to provide some help.

      Comment by Mukarram Mukhtar — December 6, 2010 @ 3:59 pm

  3. Hi Mukarram,
    I reallllly like your code but I would like to ask you to send the whole project for me please
    so I can try it since I didn’t include the icons

    Thank you in Advance,
    Monee

    Comment by Monee Karim — January 22, 2011 @ 5:46 pm

    • Sorry I don’t mea the whole thing
      I just want to try this code but I don’t have access to the icons
      so is it possible to send it to me plz!

      Comment by Monee Karim — January 22, 2011 @ 6:14 pm

  4. Hi Mukarram,

    I cannot manage to move icons on chess board. When i debug the code it cannot reach mouse event part. Please help me.

    Comment by Abdulrezzak — January 28, 2011 @ 8:22 pm

    • Are you sure you copied the whole source code? Were you able to find the following lines in source? This method is mouse event.

      // This method captures the move on the chess board and then make
      // it happen, logically and physically; also, it sends the move to
      // the other client
      public void mouseClicked(MouseEvent e)
      {

      Finaly, I can send you the whole source code with the images and everything, but you have to ask little nicer 🙂

      Comment by Mukarram Mukhtar — January 28, 2011 @ 8:40 pm

      • Ok thank you. You are very nicer

        Comment by Abdulrezzak — January 28, 2011 @ 9:12 pm

      • Ok, thank you. So was that just a comment, or you are actually asking for the source code?

        Comment by Mukarram Mukhtar — January 31, 2011 @ 3:15 pm

  5. Mukarram Mukhtar,
    Can you please email me the whole source code, i tried to runi it but i need the image icon.. please I need it urgently, i want to debug it and understand the steps.. get back to me ASAP please 🙂

    Comment by Nadia — January 30, 2011 @ 3:20 pm

  6. hi
    would u plz teach me from the very begining how to create a project and
    where to write these codes,i really need help , does this code need a jframe
    or it is created by the codes ,i mean we should ourself add a jframe or not !
    and would u plz send your whole project for me??
    thanks alot

    Comment by sisi — February 5, 2011 @ 2:43 pm

  7. will all of the above code go into the same class?

    Comment by GT — April 1, 2011 @ 5:14 pm

  8. Mukarram Mukhtar,

    I am currently working on phase 3 of a semster long project to create a chess application in java and I am absolutely struggling. I would greatly appreciate any help. I am new to programming and new to these forums. May I please view your code to use as a reference for building my project? Thanks for your consideration.

    Comment by GT — April 1, 2011 @ 5:18 pm

  9. Hi,
    I love the code, could you send me images of the pieces please?

    Thanks

    Comment by Chris Harris — April 11, 2011 @ 4:31 pm

  10. Dear Mr. Mukarram Mukhtar,

    I was deeply impressed with the description and images of your chess board program. Can you please send me the whole project code, with icons? I would greatly appreciate it. I am building a chess robot with lego nxt, and wanted to have a simple chess gui to check the board onscreen, compared to real life. Thank you kindly. I would of course cite your program in our chess robot. Many thanks in advance.

    Comment by JJS — June 7, 2011 @ 5:02 am

    • I have been building a chess program of my own and was looking around for an example of how to draw a chessboard in Java.
      I got your example to run in Eclipse, but I don’t have the icons for displaying the pieces. Is there any way you could send
      me the png files for the icons. Many thanks in advance. I’d appreciate it very much.

      Comment by Brent Martin — October 8, 2011 @ 5:27 pm

  11. hi Mr Mukarram Mukhtar
    Thank you for the tutorial very, interresting work. Having difficulties getting the icons to appear on the board.
    Please could you help, maybe with the code that will allow the icon to appear

    Comment by Tina — October 26, 2011 @ 12:58 pm

  12. hi i really love u code !! but i can not display the icons only the chess board … can you send me the whole thing with image icons? thank you !!! my email is eric7704@hotmail.com

    Comment by eric — November 6, 2011 @ 7:20 pm

  13. hi Mukarram Mukhtar,

    i really liked ur code !!its easy to understand.bt i cannot see icons in the chessboard.i have to make project for my college.can u please send me the whole project with icon.? thank you in advance.will wait for ur reply………:)

    Comment by parmeet kaur — December 27, 2011 @ 11:00 am

  14. hi your code is great but there are a few things i dont understand what does these lines mean

    int intX = (pnlTemp.getX()/57);
    int intY = (pnlTemp.getY()/57);

    why did you divide it by 57

    Comment by Raymond — January 23, 2012 @ 2:23 pm

    • Raymond, the division by 57 is because the pnlMain’s width and height is 460 pixels and pnlMain is divided into 64 equal panels (horizontally and vertically), now wherever user clicks to make a move, we have to convert the X and Y of the cursor into the x and y index of a 2-dimensional array strChessBoard. These exact numbers are not mandatory, you can change these numbers if you change the size of the board etc. Try playing around with these numbers, only then you’ll understand what I’m talking about. Good luck! 🙂

      Comment by Mukarram Mukhtar — January 23, 2012 @ 3:31 pm

  15. Hiya is there anyway u can send me the full code?
    Thanks

    email add: ishy61@gmail.com

    Comment by ishy — March 5, 2012 @ 8:48 pm

  16. Any help on controlling the black pieces ?

    Comment by Liam — March 11, 2012 @ 7:19 pm

    • The black pieces will be moved by opponent, in this case, the computer. While in the complete game computer will have the ability to make moves, in this particular demo, I was just showing how to quickly and easily draw a chess board in JAVA. This can give you guys a head start if you’re writing a chess game of your own. I’ll be more than happy to send you the source code if you’re interested. Lemme know 🙂

      Comment by Mukarram Mukhtar — March 11, 2012 @ 11:01 pm

  17. Hi Mukarram. Can you send me whole source code with images?
    Thank you:) my email -> ehly_12@hotmail.com

    Comment by Eva — March 19, 2012 @ 8:02 pm

  18. Sorry, I have created the folder “images” and put all of image icons into it, then put the folder in the same folder with the source code, but there haven’t been any icon displayed at all. How can I do now ? 😦

    Comment by Thai — March 31, 2012 @ 6:05 am

    • I’ve sent you the project source code in a zip file. It has images folder and everything set up. You can then replace my images with yours. the name of the image files and their extension MUST be the same as given in the source code. I hope that helps.

      Comment by Mukarram Mukhtar — April 1, 2012 @ 2:14 pm

      • Hi Mukarram, can you send me the whole source code too? Thanks!

        Comment by Xavier — June 2, 2012 @ 9:25 am

      • Your coding and approach to the problem is very impressive. Can you please send me the full source code to my email such that i can learn a lot. Thanks in advance for sending

        Comment by srikanth — June 27, 2012 @ 8:54 pm

  19. Hi Mukartram, Can you please send me whole source code with images?
    Thank you:) my email is curacao@hotmail.com

    Comment by sen — July 13, 2012 @ 11:55 am

  20. Hi Mukarram,
    I am making chessmaster club as my final year projec, here i want make player’s to play game.using website so i requried client-server architecture for multiple player, so please i need your valuable help in this, and one more thing, those player who want to watch the game can watch it live please also suggest me for this, and thank you in advance

    Comment by Amol — July 15, 2012 @ 1:49 pm

  21. hi

    Your code is well written and easy to understand!! I am making a chess board .can u please send me the icons for the different pieces..? thanks

    Comment by Nidhi — July 22, 2012 @ 4:19 am

  22. Hi!
    I am newby in Java, and have ineterest in Java Games programming,
    Please assist me with the whole Source CODE………..

    Please, Help with the icons too….

    Thanks in Advance

    Comment by Chikondi — October 8, 2012 @ 6:52 pm

  23. Hi Mukaram!

    I really need your help. Could you please send me the whole project along with images to my e-mail: london_guy@msn.com

    Comment by Azzum Waqar — November 2, 2012 @ 6:19 pm

  24. Hello Mukaram !

    I’m currently first semester and I am making a simple chess program in Java. Can you please send me the whole project with images to my email – zhaniel@abv.bg

    Thank you in advance 🙂

    Comment by Zhaniel Genev — November 11, 2012 @ 2:52 pm

  25. Hello Mukaram!

    Very nice program indeed, can you please send me the whole project with the images to my email – sahilsatsangi@hotmail.com

    Thankyou 🙂

    Comment by sahil satsangi — November 21, 2012 @ 1:40 pm

    • haiiiiiiiiiii mukaram,

      i want the whole code or a war file with images …. can u please send me those ??

      tommorrow i have an interview on this ..they said me to design this ..and i am very happy that i got it in my first search with ur courtesy

      can u please do me this favor .. my e-mail id is satyasagar76@gmail.com

      Comment by satya — December 19, 2012 @ 8:14 am

  26. Hi!
    I am newby in Java, and have ineterest in Java Games programming,
    Please assist me with the whole Source CODE………..

    Please, Help with the icons too….

    Thanks in Advance

    Comment by deep — December 11, 2012 @ 12:05 pm

  27. Hi Mukarram,
    Its a great article to learn about Java desktop programming and chess gaming..
    I will greatly appreciate if you can please email me the chess piece images?
    Thank you
    Sansun

    Comment by Sansun — January 8, 2013 @ 3:35 pm

  28. do you take commission? If i ask you to make me a chess engine using bit boards. or if u can guide me please. I am really scared. 😦 salam

    Comment by Azzum Waqar — January 22, 2013 @ 4:55 pm

  29. Hey Mukkaram, I looked at your code and looks like it can be helpful for my assignment. However my assignment does not require GUI, but it will help me implement the methods and objects. Is it possible for you to send me the code. I will be very thankful to you.

    Comment by Mir Shah — February 28, 2013 @ 9:11 pm

  30. Can u please send me the icons for the different pieces. I need to develop a chess game
    please help me and forward to mail

    Comment by Rakesh — March 11, 2013 @ 9:23 am

  31. Hello Mukaram!

    can u please send me this project to my id.
    thnku.

    Comment by vidhu — March 31, 2013 @ 6:28 pm

  32. wow..i like the board , it looks so nice..may you please email me all the codes with moving pieces..

    Comment by Hosia — April 9, 2013 @ 11:51 am

  33. please send me whole code with having images
    my mail id is
    vinaysingh.singh254@gmail.com

    Comment by vinay singh — April 12, 2013 @ 5:38 pm

  34. Hello Mukarram,

    After many years of working with databases, I’m studying java.

    I wanted to use your Chess board to do the Knight’s Tour question.

    I’ve found some (other) chess piece icons online.
    But after I put them in the images directory, they are not showing up when I run the program.

    Is there a secret to get them to show up? What is it?

    Thanks a lot,

    Rodger

    Comment by Rodger — April 20, 2013 @ 4:14 pm

  35. super nice

    Comment by saru — January 28, 2014 @ 5:10 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: