import objectdraw.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Factorial extends Controller implements ActionListener  
{
    private static final int FONTSIZE = 24,
                             INPUT_WIDTH = 5;

  // Recursive algorithm to compute powers
  public int factorial(int n) {
      if (n == 0) {
        return 1;    
      } else {
        return n*factorial(n-1);    
      }
  }

  private JTextField input;
  private JLabel l0;
  private JButton goButton;
  private JLabel answer;

  public void begin() {
    l0 = new JLabel("factorial(", JLabel.RIGHT);
    input = new JTextField("0", INPUT_WIDTH);
    answer = new JLabel(") = 0");
    goButton = new JButton("Go!");

    JPanel panel = new JPanel(new GridLayout(1,3));

    input.setFont(new Font("System", 0, FONTSIZE));
    l0.setFont(new Font("System", 0, FONTSIZE));
    answer.setFont(new Font("System", 0, FONTSIZE));

    panel.add(l0);
    panel.add(input);
    panel.add(answer);
    
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(goButton);

     Container contentPane = getContentPane();
     contentPane.add(panel, BorderLayout.NORTH);
     contentPane.add(buttonPanel, BorderLayout.CENTER);
     
    goButton.addActionListener(this);
    input.addActionListener(this);
   // put at end of all methods that change the layout
    validate();
  }

  // calculate power
  public void actionPerformed(ActionEvent e) {
    int n = Integer.parseInt(input.getText());
    answer.setText(") = " + factorial(n));
  }
}
