I would like to create an alternating checkerboard pattern in Java, preferably u
ID: 3886401 • Letter: I
Question
I would like to create an alternating checkerboard pattern in Java, preferably using for loops. The method that I need to call is this:
The dimensions of the image are to be 1000 x 600 pixels. The checkerboard must fill the entire image, this is the code I have written so far, but it does not work.
Each square MUST BE 100 pixels by 100 pixels. The pixels are ordered in row major form.
The pattern I am trying to recreate is this one in the background of this image:
From what I can see, the pattern must be made with fb.setPixelFB(x-coordinate, y-coordinate, color)
public void setPixelFB (int x, int y, Color c) int index = (y*width + x); try pixel-buffer[ index] = c. getRGB(); catch (ArrayIndex0utofBoundsException e) System.err.println("FrameBuffer: Bad pixel coordinate "x + ", " y "" /Te.printStackTrace (System.exr)Explanation / Answer
All you have to do is replace your code by below code to make it working. And you will also have to change the way you are processing pixel_buffer array. In my code, I've stored x and y coordinate in a 2 dimensional array. So you can directly apply 2 nested loops and pick values from this array and draw rectangles
boolean isFirstColor=true;
private void test(){
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 6; j++) {
if (isFirstColor) {
fb.setPixelFB(i*100,j*100,firstColor)
} else {
fb.setPixelFB(i*100,j*100,secondColor)
}
isFirstColor=!isFirstColor;
}
isFirstColor=!isFirstColor;
}
}
private void setPixelFB(int x, int y, Color c){
pixel_buffer[x][y]=c.getRGB();//your pixel_buffer array should be 2 dimensional
}