/* CalculatorButtons.java        Authors: Koffman & Wolz
 * Applet for demonstrating grid layout.
 * Uses Swing and AWT.
 */
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class CalculatorButtons extends JApplet
                               implements ActionListener {

  private JButton[] digitButtons;
  private JTextField result = new JTextField(10);

  public void init() {
    String[] buttonLabels =  {"1", "2", "3", "4", "5", "6",
                              "7", "8", "9", "C", "0", "."};

    // Create an array of buttons.
    digitButtons = new JButton[buttonLabels.length];

    // Create a 4 x 3 grid for placement of buttons.
    JPanel buttonGrid = new JPanel();
    buttonGrid.setLayout(new GridLayout(4, 3));

    // Create a button with each button label, add it to buttonGrid,
    //   and register the applet as a listener.
    for (int nextBut = 0; nextBut < digitButtons.length; nextBut++) {
      digitButtons[nextBut] = new JButton(buttonLabels[nextBut]);
      buttonGrid.add(digitButtons[nextBut]);
      digitButtons[nextBut].addActionListener(this);

    }

    JLabel instruct = new JLabel("Press a button");
    getContentPane().add(instruct, BorderLayout.NORTH);
    getContentPane().add(buttonGrid, BorderLayout.CENTER);
    getContentPane().add(result, BorderLayout.SOUTH);
  }

  public void actionPerformed(ActionEvent aE) {
    Object whichButton = aE.getSource();
    for (int nextBut = 0; nextBut < digitButtons.length; nextBut++) {
      if (whichButton == digitButtons[nextBut])
        result.setText("You pressed " +  digitButtons[nextBut].getText());
    }
  }
}