I am trying to create a chess board using the fillrect function in java.The code doesn't seem to be working and adds only the first statement in the frame.Even if I remove the for loop (that prints 64 squares ) and make only 2 add statements,it still prints only the first of them.Here is the code:
import javax.swing.* ;
import java.awt.* ;
public class ChessBoard extends JFrame {
private int i;
public ChessBoard (){
setLayout(new GridLayout(8,8,0,0));
// there are 64 squares
for(i=0; i<64 ;i++){
if ((i % 2) == 0) //switches between black and white squares
add(new DrawRect("WHITE"));
else
add(new DrawRect("BLACK"));
}
}
}
class DrawRect extends JPanel{
private String ngjyra = "BLACK";
public DrawRect(String b) {
ngjyra = b ;
}
@Override
protected void paintComponent (Graphics g){
super.paintComponent(g);
if (ngjyra.equals("BLACK"))
g.setColor(Color.BLACK);
else
g.setColor(Color.WHITE);
g.fillRect(getX(), getY(), getWidth(), getHeight());
//add the square with the specified color
}
}