Search code examples
javachess

Grid Color Change


can somebody please help me create a chess like board. I need to change the color the grid to black and white. I tried to use a an if statement if (r % 2 = 0) then rectfilcolor, but it colors the hall row.

package grid;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;

public class grid extends JPanel {
    public static int High=640;
    public static int width=617;
    public static int row=3,column=3;
    public static JFrame Frame;

    public static void main(String[] args) {
        grid gride= new grid();
        Frame= new JFrame();
        Frame.setSize(width, High);
        Frame.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE);
        Frame.setVisible(true);
        Frame.add(gride);
        gride.setBackground(Color.cyan);
    }

    public void paintComponent(Graphics g) {
        for (int r=0; r<4; r++) {
            g.drawLine(r*(600/3), 0, r*(600/3), 600);

            for (int c=0; c<4; c++) {
                 g.drawLine(0,(c*(600/3)), 600, (c*(600/3)));
            }
        }
    }
}

-------------------------------------Edited----------------------------------

public void paintComponent(Graphics g){

      for (int r=0;r<4;r++){
          g.drawLine(r*(600/3), 0, r*(600/3), 600);
          if (r%2!=0){
              g.setColor(Color.white);
              g.fillRect(r*(600/3), 0, r*(600/3), 600);
          }


      for (int c=0;c<4;c++){
          g.drawLine(0,(c*(600/3)), 600, (c*(600/3)));
          if(c%2!=0){
              g.setColor(Color.black);

              g.fillRect(0,(c*(600/3)), 600, (c*(600/3)));
          }

      }
      }
      }
    }

Solution

  • Always remember to call super.paintComponent(g) to initialize the JPanel canvas correctly.

    You can use g.fillRect(x, y, width, height) method to draw each chess cell. Use g.setColor(color) to change the color of the painting.

    Therefore:

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
    
        Color[] colors = {Color.BLACK, Color.WHITE};
        int lengthUnit = (600 / 3);
        for (int row = 0; row < 3; ++ row) {
            for (int col = 0; col < 3; ++col) {
                g.setColor(colors[(row + col) % 2]); // alternate between black and white
                g.fillRect(row * lengthUnit, col * lengthUnit, lengthUnit, lengthUnit);
            }
        }
    }
    

    Edit: you are almost there, just need to remove some redundant statements in the nested for loop...

    for (int r = 0; r < 4; r++) {
            for (int c = 0; c < 4; c++) {
                if ((c + r) % 2 != 0) {
                    g.setColor(Color.black);
                } else {
                    g.setColor(Color.white);
                }
                g.fillRect(r * (600 / 3), (c * (600 / 3)), 200, 200);
            }
        }