Write a program in java to design a checkboard with the following criteria’s Dis
ID: 3693947 • Letter: W
Question
Write a program in java to design a checkboard with the following criteria’s Displays a frame containing 64 squares arranged in eight rows and eight columns. Each square is 25 pixels by 25 pixels. The colors of the squares alternate between red and black, starting with a red square in the upper-left corner. Sample code //Download the jpb.zip folder unzip/extract all files and place in the same location as your Checkerboard program // DOWNLOAD the JPB here //This program will draw a checkerboard in a Drawable Frame of the size //200 X 200 pixels in the colors of red and black you can set your own frame size import java.awt.*; import jpb.*; public class Checkerboard { public static void main (String[] args) { DrawableFrame df = new DrawableFrame("Checkerboard"); df.show(); df.setSize(200, 200); Graphics g = df.getGraphicsContext(); // your code starts here //your code end here df.repaint(); } }Explanation / Answer
import java.awt.Color;
import java.awt.Graphics;
public class Checkerboard {
public static void main(String[] args) {
int rows = 8; // 8x8 for 64 squares
int columns = 8;
int squareHeight = 25; // 25px height & width
int squareWidth = 25;
Color[] colors = {new Color(0xFF0000), new Color(0x000000)}; // colors to alternate between
int width = rows * squareWidth;
int height = columns * squareHeight;
DrawableFrame df = new DrawableFrame("Checkerboard");
df.show();
df.setSize(width, height);
Graphics g = df.getGraphicsContext();
int currentColor = 0;
for (int i = 0; i < columns; i++) {
// columns
int heightPlacement = squareHeight * i;
for (int j = 0; j < rows; j++) {
// rows
currentColor = changeColor(currentColor);
Color usedColor = colors[currentColor];
g.setColor(usedColor);
g.fillRect(squareWidth * j, heightPlacement, squareWidth, squareHeight);
}
if(rows % 2 == 0){
// if the number of rows is even, we'll need to change the first color on the next line.
currentColor = changeColor(currentColor);
}
}
df.repaint();
}
public static int changeColor(int currentColor){
// assume that we're alternating between two colors..
if(currentColor == 0){
return 1;
}else{
return 0;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.