import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;

/*A "2D" array of Buttons
- make a 1D array of buttons, put it in a grid
- make another array to track things in it
- translate out the tracking array's values into the 1D array when "printing"
*/

public class Buttons2DArray extends Applet implements ActionListener
{
    int row = 10;
    int col = 10;
    int total = row * col;
    JButton a[];  //1D array to simulate a 2D one
    Color tracker[] [];  //2D array to track colours in 1D button array

    public void init ()
    {
	Panel p = new Panel (new GridLayout (row, col, 0, 0));

	//initialize tracking array to have all black backgrounds
	tracker = new Color [row] [col];
	for (int i = 0 ; i < row ; i++)
	{
	    for (int j = 0 ; j < col ; j++)
	    {
		tracker [i] [j] = Color.black;
	    }
	}

	//declare a new array of buttons
	a = new JButton [total];

	//initialize each of the buttons in the array
	//with an empty label
	for (int i = 0 ; i < total ; i++)
	{
	    a [i] = new JButton ("    ");
	    a [i].addActionListener (this);
	    a [i].setActionCommand ("" + i);
	    a [i].setBackground (Color.black);
	    p.add (a [i]);
	}

	add(p);
    }


    public void actionPerformed (ActionEvent e)
    { //To handle the button array - invoked when button is clicked

	//get the number of the button from getActionCommand
	//convert it to an int and store it in i
	int pos = Integer.parseInt (e.getActionCommand ());

	//find i and j
	int x = pos / row;
	int y = pos % row;

	//set tracker to have a new background colour
	if (tracker [x] [y].equals (Color.blue))
	    tracker [x] [y] = Color.yellow;
	else 
	    tracker [x] [y] = Color.blue;

	//update the buttons on the screen
	int move = 0;
	for (int i = 0 ; i < row ; i++)
	{
	    for (int j = 0 ; j < col ; j++)
	    {
		a [move].setBackground (tracker [i] [j]);
		move++;
	    }
	}

    }
}

