JAVA系列之画国际象棋盘

时间:2022-03-07 10:59:36

import java.awt.*;

import javax.swing.JPanel;
public class Chess extends JPanel {
 int x = 0;
 int y = 0;
 boolean isWhite = true;
 public Chess(){
 }
public void paintComponent(Graphics g){
  super.paintComponent(g);
  int width = this.getWidth()/8;
  int height = this.getHeight()/8;
  for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
          if (isWhite) {
            g.setColor(Color.white);
            isWhite = false;
          }
          else {
            g.setColor(Color.black);
            isWhite = true;
          }

          g.fillRect(x, y, width, height);
          x += width;
        }

        if (i % 2 == 0)
          isWhite = false;
        else
          isWhite = true;
        x = 0;
        y += height;
      }
    }
public Dimension getPreferredSize(){
     return new Dimension(80, 80);
 }
}
import java.awt.GridLayout;

import javax.swing.JFrame;


public class TestChess extends JFrame{
 public TestChess(){
  setLayout(new GridLayout());
  add(new Chess());
 }

 
 public static void main(String[] args) {
  TestChess frame = new TestChess();
  frame.setSize(400,200);
  frame.setTitle("Exercise13_3");
  frame.setLocationRelativeTo(null);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
  
  

 }

}