I have code which creates a chessboard. It was working recently but I'm not sure what I changed. When I run it an empty window appears.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
public class Chess extends JFrame implements ActionListener {
JButton[][] a = new JButton[8][8]; //This is the individual squares of the game board
JPanel board = new JPanel(); //The first instance of the game board
int lineCounter = 0; //Records the current horizontal row
String[][] pieceList = new String[8][8]; //This list has the game pieces recorded in it
public Chess() {
//Create the board
setTitle("CHESS");
setSize(600,600); //Sets the window size to 600x600
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(8,8)); //Sets the game board to an 8x8 grid
for (int i = 0; i < 8; i++) { /*This nested loop determines the colour of the the board squares, and which colour pieces should go
onton which tiles.*/
for (int j = 0; j < 8; j++){
if((i+j)%2 == 0 && lineCounter < 3) { //This if statement sets the top part of the game board, and sets the red pieces
pieceList[i][j] = "RedPiece";
a[i][j] = new JButton();
a[i][j].setBackground(Color.black);
board.add(a[i][j]);
} else if ((i+j)%2 == 0 && lineCounter >= 5) { //This if statement sets the bottom of the board, and the blue pieces
pieceList[i][j] = "BluePiece";
a[i][j] = new JButton();
a[i][j].setBackground(Color.black);
board.add(a[i][j]);
} else if ((i+j)%2 == 0 && 3 <= lineCounter && lineCounter < 5) { //This if statement sets the middle of the game board
pieceList[i][j] = null;
a[i][j] = new JButton();
a[i][j].setBackground(Color.black);
board.add(a[i][j]);
} else {
pieceList[i][j] = null;
a[i][j] = new JButton();
a[i][j].setBackground(Color.gray);
board.add(a[i][j]);
}
}
lineCounter++;
}
}
A for loop follows that adds the new JButtons and sets the background colours. The setVisible(true)
is in a separate class. I'll be happy to post more code but I'm sure the problem is here somewhere. I may have left something out. Currently, I'm not adding the pieces game pieces yet.
This is the driver class I used:
public class ChessGUI {
public static void main(String[] args){
Chess run = new Chess();
run.setVisible(true);
}
}