| This is a trivial change. I pulled out some comments,
and added calls to the Canvas method
getSize. This might not work for you.
If you get a gray area where the Life board should be (instead of blue and white ovals), your browser probably doesn't understand getSize. You need a more modern browser, or you need to view this applet using appletviewer. To see why this is a cool thing to do, run the applet using appletviewer, and change the size of the applet window. Everything is automatically resized to fit. |
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 ()
{
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
}
}
class MyCanvas extends Canvas
{
int boardSize;
boolean board[][];
MyCanvas (boolean[][] board, int boardSize)
{
this.board = board;
this.boardSize = boardSize;
}
public void paint (Graphics g)
{
// Get the size, not of the applet, but of the canvas itself.
// Among other reasons, this looks nicer if the window is resized.
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);
}
}
}
}