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.