Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need to rewrite this code that displays a checkerboard in which each white and

ID: 3627590 • Letter: I

Question

I need to rewrite this code that displays a checkerboard in which each white and black cell is a JButton. I need to draw a checkerboard on a JPanel using the drawing methods in the Graphics class.

import java.awt.*;

import javax.swing.*;

public class Exercise12_10 extends JFrame {
public static void main(String[] args) {
Exercise12_10 frame = new Exercise12_10();
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Exercise12_10");
frame.setVisible(true);
}

public Exercise12_10() {
// Create panel p1 add three buttons
JPanel p1 = new JPanel(new GridLayout(8, 8));
add(p1);

JButton[][] buttons = new JButton[8][8];
boolean isWhite = true;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
buttons[i][j] = new JButton();
p1.add(buttons[i][j]);
if (isWhite) {
buttons[i][j].setBackground(Color.WHITE);
isWhite = false;
}
else {
buttons[i][j].setBackground(Color.BLACK);
isWhite = true;
}
}

if (i % 2 == 0)
isWhite = false;
else
isWhite = true;
}
}
}

Explanation / Answer

import java.awt.*;
import javax.swing.*;

public class Exercise12_10 extends JPanel
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Exercise12_10");
frame.add(new Exercise12_10());
frame.pack();
frame.setVisible(true);
}

public Exercise12_10()
{
setPreferredSize(200, 200);
}

public void paint(Graphics window)
{
int width = getWidth()/8;
int height = getHeight()/8;
for(int r = 0; r < 8; r++)
{
for(int c = 0; c < 8; c++)
{
if(r+c%2 == 0)
window.setColor(Color.white);
else
window.setColor(Color.black);
window.fillRect(c*width, r*height, width, height);
}
}
}
}