Friday, July 19, 2024

Drawing ChessBoard in Java Swing

 // Draw ChessBoard in Java Swing

import java.awt.*;

import javax.swing.*;


public class ChessBoard extends JFrame

{

public ChessBoard()

{

super("ChessBoard Example");

setDefaultCloseOperation(EXIT_ON_CLOSE);


setSize(600,600);

setVisible(true);

}

public void paint(Graphics g)

{

int n=8;

int x,y;


for(int row=1; row<=n; row++)

{

for(int col=1; col<=n; col++)

{

Graphics2D g2d=(Graphics2D)g;


x = row*60;

y = col*60;


if((row%2==0) == (col%2==0))

{

g2d.setColor(Color.BLACK);

g2d.fill3DRect(x,y,60,60,true);

}

else

{

g2d.setColor(Color.WHITE);

g2d.fill3DRect(x,y,60,60,true);

}

}

}

}

public static void main(String args[])

{

new ChessBoard();

}

}


Output :-