Version 6

Now we make the button do something, by adding an ActionListener to it. We do this by creating a new class Step that implements ActionListener and includes the one required method, actionPerformed.

We made Step an inner class, because we only want to use it right here, but we could have made it a plain old (top-level) class.

actionPerformed ignores its argument, and just flips all the ovals, blue to white and white to blue. Then it paints the changes onto the canvas, and calls the applet method repaint to make the changes visible.

Again, if this doesn't work, you either aren't using Java 1.1, or your browser doesn't support all of Java 1.1.

Top     Version 5     Version 7    

Source code:

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;    // needed for ActionListener

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

  public void init ()
  {
    setLayout (new BorderLayout ());

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

    // Finally, add code to make the button do something
    stepButton.addActionListener (new Step ());

    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
  }

  class Step implements ActionListener
  {
    public void actionPerformed (ActionEvent e)
    {
      // Just make some changes...
      for (int i = 0; i < boardSize; i++)
	for (int j = 0; j < boardSize; j++)
	  board[i][j] = ! board[i][j];

      // ...then make the changes visible.
      canvas.paint (canvas.getGraphics ());
      repaint ();
    }
  }
}

class MyCanvas extends Canvas
{
  int boardSize;
  boolean board[][];

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

  public void paint (Graphics g)
  {
    Dimension d = getSize ();
    int cellWidth = d.width / boardSize;
    int cellHeight = d.height / boardSize;

    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 * cellWidth, j * cellHeight, cellWidth, cellHeight);
      }
    }
  }
}