Version 4

This one adds a "Step" button (which doesn't actually do anything yet). Things are starting to get a little complicated here.

Before, the paint method just painted directly to the applet. Now, we want to separate the applet into two areas, one containing the button, and one containing the Life board. To do this, we use a layout manager, BorderLayout, and put the button directly in the NORTH part.

We can't paint directly into the CENTER part, though; we have to put a Canvas in the center, and paint on it. The simplest way of doing this is to move our paint method from the Life class (where we no longer need it, because we're not painting directly onto the applet itself) to the MyCanvas class.

Also, notice that because the button takes up some room, the bottom of the Life board is being chopped off. We have to do something about that.

Top     Version 3     Version 5    

Source code:

import java.awt.*;
import java.applet.Applet;

public class Life extends Applet
{
  int boardSize = 10;
  boolean[][] board = new boolean[boardSize][boardSize];
  Button stepButton;
  MyCanvas canvas;

  public void init ()
  {
    // Now using a layout manager, with a button and a canvas.

    setLayout (new BorderLayout ());

    stepButton = new Button ("Step");
    add (BorderLayout.NORTH, stepButton);

    canvas = new MyCanvas (board, boardSize);
    add (BorderLayout.CENTER, canvas);

    for (int i = 0; i < boardSize; i++)
      for (int j = 0; j < boardSize; j++)
        board[i][j] = (i + j) % 3 == 0; // diagonal pattern
  }
}

/* If you're going to use a canvas, you have to make your own class
   that extends Canvas, so that you can define a paint () method for
   it. */
 
class MyCanvas extends Canvas
{
  int boardSize;
  boolean board[][];

  MyCanvas (boolean[][] board, int boardSize)
  {
    this.board = board;
    this.boardSize = boardSize;
  }

  /* Moved paint () from applet Life to canvas MyCanvas; this way,
     it paints on the canvas, not on the applet itself.  This is
     necessary because the canvas now covers that part of the applet. */

  public void paint (Graphics g)
  {
    int cellSize = 20; // too inflexible

    for (int i = 0; i < boardSize; i++) {
      for (int j = 0; j < boardSize; j++) {
        if (board[i][j])
	  g.setColor (Color.blue);
	else
	  g.setColor (Color.white);
	g.fillOval (i * cellSize, j * cellSize, cellSize, cellSize);
      }
    }
  }
}