0

I'm creating a checkerboard game using Java & Swing. To make the checkerboard, I am using the GridLayout for my JFrame. The output is incorrectly shown. What I get instead is 9 columns and 7 rows + an extra row with 2 squares. The alternating color works.

I have specified the number of rows and columns (8x8, like a real checkerboard) and use a for loop to add JPanels to the JFrame (with alternating color). I've played around with number of iterations on the loop and the size of my grid, but that hasn't worked so far.

The relevant method:

private void createBoard() {
        f = new JFrame("Checkers");

        for (int i = 0; i <= 64; i++) {
            JPanel panel = new JPanel();
            if (i % 2 == 0) {
                panel.setBackground(Color.LIGHT_GRAY);
            } else {
                panel.setBackground(Color.DARK_GRAY);
            }
            f.add(panel);
        }

        f.setLayout(new GridLayout(8,8));
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.setSize(windowSize, windowSize);
        f.setVisible(true);
    }

I am expecting this method to create a JFrame filled with 64 panels (8 rows and 8 columns into a square frame), each panel being an alternate color.

2
  • I am expecting this method to create a JFrame filled with 64 panels, each panel being an alternate color - when you ask a question you need to also tell us what happens. I'm guessing your don't see alternate colors of squares but columns with the same color. See: stackoverflow.com/questions/2561690/… for an example.
    – camickr
    Mar 28, 2019 at 19:54
  • @camickr Edited for clarification, thank you. The colors are not the problem.
    – user10071389
    Mar 28, 2019 at 20:14

1 Answer 1

1
for (int i = 0; i <= 64; i++) {

You are adding 65 panels.

The code should be:

for (int i = 0; i < 64; i++) {

The GridLayout constructor doesn't work as you expect:

f.setLayout(new GridLayout(8,8));

The code should be:

f.setLayout(new GridLayout(0,8));

Now the components will wrap automatically when they reach the 8th column adding as many rows as is necessary.

Also, typically you would set the layout of a panel BEFORE you add the components. In the case of a GridLayout it doesn't matter, but it is a good habbit.

The colors are not the problem

Once you fix the above problem it will become the new problem. My original comment addresses the issue. The problem is your logic for determining how to color the panels.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.