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 Mapper extends Applet implements ActionListener
{
    int row = 5;
    int col = 5;
    int total = row * col;
    JButton a[];  //1D array to simulate a 2D one
    String 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 String [row] [col];
	for (int i = 0 ; i < row ; i++)
	{
	    for (int j = 0 ; j < col ; j++)
	    {
		tracker [i] [j] = "tree.gif";
	    }
	}
	//manually set some places
	tracker [3] [2] = "house.gif";
	tracker [2] [1] = "house.gif";
	tracker [1] [1] = "house.gif";
	//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].setPreferredSize (new Dimension (46, 46));
	    a [i].addActionListener (this);
	    a [i].setActionCommand ("" + i);
	    p.add (a [i]);
	}
	update ();
	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 ("tree.gif"))
	    tracker [x] [y] = "house.gif";
	else
	    tracker [x] [y] = "tree.gif";

	update ();

    }


    public void update ()
    { //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].setIcon (createImageIcon (tracker [i] [j]));
		move++;
	    }
	}
    }


    /**
    Makesanimageiconto go on a button
    @parampathisavalid path to a jpg or gif image
    @returnanImageIcon,ornull if the path was invalid.
    Directlyfrom:http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/index.html#RadioButtonDemo
    */
    protected static ImageIcon createImageIcon (String path)
    { //change the red to your class name
	java.net.URL imgURL = Mapper.class.getResource (path);
	if (imgURL != null)
	{
	    return new ImageIcon (imgURL);
	}
	else
	{
	    System.err.println ("Couldn't find file: " + path);
	    return null;
	}
    }
}

