//  File:  SingleListernerHandler\SingleListenerHandler.java

//
//  Demonstrate SingleListenerHandler
//  a single listener/handler shared among a collection of buttons
//


import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/**
*   Using a single Listener and a single Handler for a whole bunch of Buttons
*/

public class SingleListenerHandler extends Applet {

    /**
    *   Set up the background environment
    *   Create and initialize the array of buttons
    */
    public void init() {
        setLayout(new GridLayout(M, N, 20, 20));
        setBackground(Color.GRAY);
        ActionListener actionListener = new ButtonHandler();
        btnArray = new Button[MN];
        for (int i = 0; i < MN; i++) {
            Button btn;
            add(btn = btnArray[i] = new Button("Button " + (char)('A' + i)));
            btn.addActionListener(actionListener);
            btn.setActionCommand("" + i);
        }
    }

    /**
    *   ButtonHandler - determine which button was clicked by retrieving
    *   the "action command" string from the button -- they've been set up
    *   to identify each button uniquely
    */
    class ButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            int btnNum = Integer.parseInt(e.getActionCommand());
            showStatus("Button number " + btnNum);
            String s = btnArray[btnNum].getLabel();
            btnArray[btnNum].setLabel((s.charAt(0) == '*') ? s.substring(2) : "* " + s);
        }
    }
 
    private Button[] btnArray;
    private static final int M = 4;
    private static final int N = 5;
    private static final int MN = M * N;
}
