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

/**
 * A brief example of a simple GUI.
 * This program just asks the user for their year of birth and outputs
 * their age.
 *
 * @author Zach Tomaszewski
 * @version 05 Dec 2008
 */
public class UserAgeGUI implements ActionListener {

  //instance variables
  // (since we need to refer to these objects again in actionPerformed method)
  private JTextField input;
  private JButton calc;
  private JLabel output;


  /**
   * Just constructs a new instance of this GUI and displays it.
   */
  public static void main(String[] args) {
    new UserAgeGUI();
  }


  /**
   * Constructs the GUI window.
   */
  public UserAgeGUI() {
    JFrame window = new JFrame("Age Calculator");
    //Did not set the close button behavior to exit the program,
    // so currently closing the window only hides it;
    // so you'll need to kill the program with Ctrl-C.

    //construct top row of 3 components
    JPanel topRow = new JPanel();

    JLabel prompt = new JLabel("Enter your year of birth: ");
    topRow.add(prompt);

    this.input = new JTextField(5);
    //register this object with the textfield so that our actionPerformed
    //method (below) will be invoked each time someone hits enter in the field
    input.addActionListener(this);
    topRow.add(input);

    this.calc = new JButton("Calculate Age");
    calc.addActionListener(this);
    topRow.add(calc);
    window.add(topRow);

    //add bottom row
    this.output = new JLabel(" ");
    window.add(output, BorderLayout.PAGE_END);

    window.pack();  //tell window to size itself properly
    window.setVisible(true);  //actually show window on the screen
  }

  /**
   * Invoked everytime something happens to one of the GUI components
   * we're listening to.
   */
  public void actionPerformed(ActionEvent ae) {
    if (ae.getSource() == this.calc  || ae.getSource() == this.input) {
      String text = this.input.getText();
      try {
        output.setText("  Your age is " + (2008 - Integer.parseInt(text)));
      }catch (NumberFormatException nfe) {
        output.setText("  You did not enter a number.");
      }
      input.setText("");
    }
  }

}








