UNB/ CS/ David Bremner/ teaching/ java/ Eggs.java
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Ellipse2D;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Eggs
{  public static void main(String[] args)
   {  EggFrame frame = new EggFrame();
      frame.setTitle("Enter number of eggs");
      frame.show();      
   }
}

class EggFrame extends JFrame
{  public EggFrame()
   {  final int DEFAULT_FRAME_WIDTH = 300;
      final int DEFAULT_FRAME_HEIGHT = 300;
      setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT);

      addWindowListener(new WindowCloser());
      
      // construct components
   
      panel = new EggPanel();

      textField = new JTextField();
      textField.addActionListener(new TextFieldListener());
      
      // add components to content pane
      
      Container contentPane = getContentPane();
      contentPane.add(panel, "Center");
      contentPane.add(textField, "South");
   }
   
   private JTextField textField;
   private EggPanel panel;
   
   private class TextFieldListener implements ActionListener
   {  public void actionPerformed(ActionEvent event)
      {  // get user input
      
         String input = textField.getText();
         
         // process user input
         
         panel.setEggCount(Integer.parseInt(input));
         
         // clear text field
         
         textField.setText("");
      }
   }

   private class WindowCloser extends WindowAdapter
   {  public void windowClosing(WindowEvent event)
      {  System.exit(0);
      }
   }
}

class EggPanel extends JPanel
{  public void paintComponent(Graphics g)
   {  super.paintComponent(g);
      Graphics2D g2 = (Graphics2D)g;
      
      // draw eggCount ellipses with random centers
      
      Random generator = new Random();
      for (int i = 0; i < eggCount; i++)
      {  double x = getWidth() * generator.nextDouble();
         double y = getHeight() * generator.nextDouble();
         Ellipse2D.Double egg = new Ellipse2D.Double(x, y, 
            EGG_WIDTH, EGG_HEIGHT); 
         g2.draw(egg);
      }
   }
   
   /** 
      Sets the number of eggs to be drawn and repaints
      the panel.
      @param count the new number of eggs
   */
   public void setEggCount(int count)
   {  eggCount = count;
      repaint();
   }

   private int eggCount;
   private static final double EGG_WIDTH = 30;
   private static final double EGG_HEIGHT = 50;
}