import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class NumberPad extends JApplet implements ActionListener {

  //components we may need to refer to later
  private JPanel top;
  private JButton[] buttons;
  private JButton enter;
  private JTextField input;
  private JLabel output;

  /** Builds the top-level JPanel of the NumberPad GUI. */
  public NumberPad() {
    //top level
    this.top = new JPanel();
    top.setLayout(new BorderLayout());

    //first row: input field
    this.input = new JTextField();
    this.input.setHorizontalAlignment(JTextField.RIGHT);
    this.input.addActionListener(this);
    top.add(input, BorderLayout.PAGE_START);  //put in top

    //create buttons
    buttons = new JButton[10];
    for (int i = 0; i < buttons.length; i++) {
      buttons[i] = new JButton("" + i);
      buttons[i].addActionListener(this);

    }

    //center row: a grid of buttons 1-9, and then 2 more buttons underneath
    JPanel center = new JPanel();
    center.setLayout(new GridLayout(4, 3));
    for (int i = 1; i <= 9; i++) {
      center.add(buttons[i]);
    }
    center.add(new Label("")); //spacer
    center.add(buttons[0]);
    this.enter = new JButton("Enter");
    this.enter.addActionListener(this);
    center.add(this.enter);
    this.top.add(center, BorderLayout.CENTER);

    //bottom row: an non-editable output/status field
    this.output = new JLabel(" ");  //a space so it has some height
    this.top.add(this.output, BorderLayout.PAGE_END);
  }

  public void actionPerformed(ActionEvent ae) {
    if (ae.getSource() == this.enter || ae.getSource() == this.input) {
      //Enter button clicked or enter pressed in input field
      this.output.setText("Entered: " + this.input.getText());
      this.input.setText("");
    }else if (ae.getSource() instanceof JButton) {
      JButton pressed = (JButton) ae.getSource();
      //one of the buttons must have been clicked: add that value to input
      this.input.setText(this.input.getText() + pressed.getText());
    }
  }

  public void init() {
    NumberPad pad = new NumberPad();
    this.setContentPane(pad.top);
  }

  public static void main(String[] args) {
    JFrame window = new JFrame("Number pad");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    NumberPad pad = new NumberPad();
    window.setContentPane(pad.top);
    window.pack();
    window.setVisible(true);
  }
}

