I'm trying to create a chess board but it doesn't work for some reason.
final int HEIGHT = 600;
final int WIDTH = 800;
final int ROW = 8;
final int COL = 8;
String COLS = "ABCDEFGH";
JFrame frame = new JFrame();
JPanel chessBoard = new JPanel();
JButton[][] chessSquares = new JButton[ROW+1][COL+1];
public void initializeGUI() {
frame.setSize(WIDTH, HEIGHT);
frame.setTitle("Chess");
chessBoard.setLayout(new GridLayout(ROW, COL));
//Creating the chessboard without the pieces
JButton temp;
for(int row=1; row<=8; row++) {
for(int col=1; col<=8; col++) {
chessSquares[row][col] = new JButton("row: " + row + "col : " + col);
if ((row+col) % 2 != 0) {
temp = chessSquares[row][col];
temp.setBackground(Color.black);
chessBoard.add(temp);
}
else {
temp = chessSquares[row][col];
temp.setBackground(Color.white);
chessBoard.add(temp);
}
}
}
frame.add(chessBoard);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
Here's an image of what it looks like :
List of things that is not working :
- Some squares are not black.
- The chessboard takes the entire space for the GUI. (I want the chessboard to take just less space. I tried using BorderLayout.South but it doesn't show the entire bord since it's not resizable.)
Note * The printing of row and cols is just to help me later. Not part of the board. It doesn't affect the color of the chessSquares(I tried it)
Edit: After turning setOpaque to true, I get this.
Is there a way to make the entire button black ?