by Dinesh Thakur Category: Swing

 

import java.awt.*;

import javax.swing.*;
public class CheckerBoardJavaExample extends JFrame
  {
      private final int ROWS = 8;
      private final int COLS = 8;
      private final int GAP = 2;
      private final int NUM = ROWS * COLS;
      private int x;
      private JPanel pnl = new JPanel
      (new GridLayout(8,8,2,2));
      private JPanel[] pnl1 = new JPanel[NUM];
      private Color clr = Color.WHITE;
      private Color clr2 = Color.BLUE;
      private Color tColor;
      public CheckerBoardJavaExample()
         {
             super("CheckerBoard in Java Swing");
             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             add(pnl);
               for(x = 0; x < NUM; ++x)
                    {
                        pnl1[x] = new JPanel();
                        pnl.add(pnl1[x]);
                        if(x % COLS == 0)
                           {
                              tColor = clr;
                              clr = clr2;
                              clr2 = tColor;
                           }
                              if(x % 2 == 0)
                              pnl1[x].setBackground(clr);
                              else
                              pnl1[x].setBackground(clr2);
                     }
          }
                    public static void main(String[] args)
                      {
                           CheckerBoardJavaExample CheckerBoard = new CheckerBoardJavaExample();
                           final int SIZE = 300;
                           CheckerBoard.setSize(SIZE, SIZE);
                           CheckerBoard.setVisible(true);
                      }
  }




About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles