Reputation: 243
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
}
}
Upvotes: 0
Views: 6365
Reputation: 21778
Your graphics uses relative coordinates with zero at the top left corner of the component, so the right way to draw rectangle is
g.fillRect(0, 0, getWidth(), getHeight());
Another issue that your colour assignment code is such that all black and all while cells make vertical stripes. Use instead the logic like
for (int row = 0; row < 8; row++)
for (int col = 0; col < 8; col++) {
boolean white = (col % 2 == 0) == (row % 2 == 0);
add(new DrawRect(white ? "WHITE" : "BLACK"));
}
Upvotes: 3
Reputation: 3822
Your problem is with getX()
and getY()
, they return the same value for each of your DrawRect
so they will be drawn one above the other. You could use setBackground
instead:
class DrawRect extends JPanel {
private Color ngjyra = Color.BLACK;
public DrawRect(Color color) {
ngjyra = color ;
setBackground(ngjyra);
}
However you still have a mistake in your loop logic, as you will see if you try the code i posted above.
Upvotes: 2