I have been asked to create a chess board and now, all right, the problem arises when I want to give color to the boxes and I do not understand why. The code below creates the board, the problem is here:
if((y+x+1)%2==0){
Casillas[y][x].setBackground(Color.BLACK);
}else{
Casillas[y][x].setBackground(Color.WHITE);
}
I get the following error
prueba.java:16: error: cannot find symbol
Casillas[y][x].setBackground(Color.BLACK);
^
symbol: method setBackground(Color)
location: class String
prueba.java:18: error: cannot find symbol
Casillas[y][x].setBackground(Color.WHITE);
^
symbol: method setBackground(Color)
location: class String
2 errors
I really do not understand, I have seen other codes to create a board, but, honestly I do not want to copy and paste, I would like to understand the code that I have created, to address this problem.
import java.awt.Color;
import java.awt.*;
import javax.swing.*;
public class prueba {
public static JPanel TableroAjedrez() {
JPanel PanelTableroAjedrez = new JPanel();
String[][] Casillas = new String[8][8];
for(int y=0; y < Casillas.length; y++) {
for(int x=0; x < Casillas[y].length; x++) {
PanelTableroAjedrez.add(new JButton(Casillas[y][x]));
if((y+x+1)%2==0){
Casillas[y][x].setBackground(Color.BLACK);
}else{
Casillas[y][x].setBackground(Color.WHITE);
}
}
}
PanelTableroAjedrez.setLayout(new GridLayout(8, 8));
return PanelTableroAjedrez;
}
public static void main(String[] args) {
JFrame Ventana = new JFrame("Tablero de Ajedrez");
Ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Ventana.setLayout(new GridLayout(1, 1));
Ventana.add(TableroAjedrez());
Ventana.setLocationRelativeTo(null);
Ventana.setPreferredSize(new Dimension(500, 500));
Ventana.pack();
Ventana.setVisible(true);
}
}