User Tools

Site Tools


checkerboard

Checker Board

Make a checkerboard

Write a graphical application that displays a checkerboard with 64 squares, alternating white and black.

Use nested loops. Hint: You can add the row and column, and if it is odd make it one color, and if it is even, you can made it the other color.

CheckerBoard.java
import java.awt.Graphics2D;
import java.awt.Rectangle;
 
/**
   This class displays a checkerboard with squares,
   alternating between white and black.
*/
public class CheckerBoard
{
   /**
      Creates a CheckerBoard object with a given number of squares.
      @param aNumSquares the number of squares in each row
      @param aSize the size of each square
   */
   public CheckerBoard(int aNumSquares, int aSize)
   {
      numSquares = aNumSquares;
      size = aSize;
   }
 
   /**
      Method used to draw the checkerboard.
      @param g2 the graphics content
   */
   public void draw(Graphics2D g2)
   {
      // your code here
   }
 
   private int numSquares;
   private int size;
}
CheckerBoardComponent.java
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Graphics2D;
 
public class CheckerBoardComponent extends JComponent
{
   public void paintComponent(Graphics g)
   {
      Graphics2D g2 = (Graphics2D) g;
 
      final int NSQUARES = 8;
 
      int size = Math.min(getWidth(), getHeight()) / NSQUARES;
      CheckerBoard cb = new CheckerBoard(NSQUARES, size);
 
      cb.draw(g2);
   }
}
CheckerBoardViewer.java
import javax.swing.JFrame;
 
/**
   This program displays a checkerboard.
*/
public class CheckerBoardViewer
{
   public static void main(String[] args)
   {
      JFrame frame = new JFrame();
 
      final int FRAME_WIDTH = 330;
      final int FRAME_HEIGHT = 360;
 
      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setTitle("CheckerBoardViewer");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
      CheckerBoardComponent component = new CheckerBoardComponent();
      frame.add(component);
 
      frame.setVisible(true);
   }
}
checkerboard.txt · Last modified: 2024/10/29 13:15 by frchris

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki