简体   繁体   中英

Building a chess board in Java

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

}
}

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"));
        }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM