import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/** Nearly the same es SheepDollyLoop but here the class DollyListener
    is not inside the class SheepDollyLoop2. 
*/
public class SheepDollyLoop2 extends Applet
{
    // Variable beloging to our class:
    TextField info;
    Button dolly;

    // We're going to bind this function to each sheep Dolly?.
    public void dollyClicked(String name)
    {
	// Change label string.
	info.setText(name + " clicked.");
    }    

    // init() is called when the applet appears on the screen.
    public void init()
    {
	// Use GridLayout to enable us to place our components in a line.
	setLayout(new GridLayout(1,6));
	
	// Our newspaper.
	info = new TextField("No dolly clicked yet.");
	add(info);
	
	// Fife identical sheep dolly will be born soon.
	for(int n=1; n <= 5; n++) { 

	    // Dolly nummer n will be born.
	    dolly = new Button();

	    // Baptism of Dolly number n.
	    dolly.setLabel("I am Dolly" + n);

	    // Public presentation of Dolly number n.
	    add(dolly);

	    // Now we change habit. Is that ethical?
	    dolly.addActionListener(new DollyListener(this, "Dolly" + n));
	}
    }
} // end SheepDollyLoop2


/** An action listener which remembers Dollys name and the applet
    which generated dolly. */
class DollyListener implements ActionListener {

    // Reference to our applet which understands the request
    // dollyClicked(String).
    final SheepDollyLoop2 applet;

    // Name of Dolly.
    final String name;

    DollyListener(SheepDollyLoop2 a, String n) {
	// remember applet.
	applet = a;
	// remember Dollys name.
	name = n;
    }

    public void actionPerformed(ActionEvent e)
    {
	// Since we are not any more inside the class SheepDollyLoop2
	// we have to specify the object which serves the request
	// dollyClicked(String).
	applet.dollyClicked(name);
    }
}

