/* CalorieCounter.java        Authors: Koffman & Wolz
 * GUI for counting calories.
 * Uses Swing, AWT, and FoodItem.
 */
import javax.swing.*;
import java.awt.event.*;

public class CalorieCounter extends JFrame
                            implements ItemListener {

  private JLabel calories = new JLabel("Calories: 0        ");
  // Array of FoodItem items.
  private FoodItem[] foods = {
      new FoodItem("8 oz. orange juice", 80),
      new FoodItem("1 cup black coffee", 0),
      new FoodItem("1 serving cornflakes with 1/2 cup skim milk", 120),
      new FoodItem("1 delicious sugar coated donut", 600),
      new FoodItem("8 oz. of skim milk", 70),
      new FoodItem("2 slices white toast, lightly buttered", 200)
      };

  // postcondition: Creates the calorie counter GUI.
  public CalorieCounter() {
    
    // Define layout manager as box layout with vertical align.
    getContentPane().setLayout(
       new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

    // Add each check box to frame and register it.
    for(int i = 0; i < foods.length; i++) {
       getContentPane().add(foods[i].getBox());
       foods[i].getBox().addItemListener(this);
    }
    
    // Add label calories to frame.
    getContentPane().add(calories);
  }

  // postcondition: Calculates and displays total calories 
  //   when a check box changes state.
  public void itemStateChanged(ItemEvent itEv) {
    // Add total calories for all boxes that are checked.
    int total = 0;
    for (int i = 0; i < foods.length; i++) {
       JCheckBox box = foods[i].getBox();
       if (box.isSelected())
          total += foods[i].getCalories();
    }
    calories.setText("Calories: " + total);
  }

  // Creates the frame and closes the frame.
  public static void main(String[] args) {
    CalorieCounter cal = new CalorieCounter();
    cal.setSize(300, 200);
    cal.setVisible(true);
    cal.setTitle("Calorie Counter");
    cal.addWindowListener(
        new WindowAdapter() {
           public void windowClosing(WindowEvent e) {
              System.exit(0);
           }
        }
    );
  }
}

