/*
 *   A Non-threaded bouncing ball demo.
 */
package threads;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;


public class BounceApplet extends JApplet
{
  public void init()
  {
    JPanel contentPanel = (JPanel)getContentPane();
    contentPanel.setLayout(new BorderLayout());
    canvas = new JPanel();
    contentPanel.add(canvas, BorderLayout.CENTER);
    JPanel panel = new JPanel();
    addButton(panel, "Start", 
              new ActionListener()
                {  
                  public void actionPerformed(ActionEvent evt)
                  {
                    canvas.setVisible(true);
                    Ball b = new Ball(canvas);
                    b.bounce();
                  }
                }
              );
    
    addButton(panel, "Close", 
              new ActionListener()
                {  
                  public void actionPerformed(ActionEvent evt)
                  {
                    canvas.setVisible(false);
                    stop();
                  }
                }
              );
    add(panel, BorderLayout.SOUTH);
  }
  
  public void addButton(JPanel panel, 
                        String title, 
                        ActionListener listener)
  {
    JButton button = new JButton(title);
    panel.add(button);
    button.addActionListener(listener);
  }
  
  private JPanel canvas;
}

class Ball
{
  public Ball(JPanel panel)
  {
    box = panel;
  }
  
  public void draw()
  {
    Graphics g = box.getGraphics();
    g.fillOval(x, y, XSIZE, YSIZE);
    g.dispose();
  }
  
  public void move()
  {
    Graphics g = box.getGraphics();
    g.setXORMode(box.getBackground());
    g.fillOval(x, y, XSIZE, YSIZE);
    x += dx;
    y += dy;
    Dimension d = box.getSize();
    if (x < 0)
    { 
      x = 0; 
      dx = -dx; 
    }
    if (x + XSIZE >= d.width)
    { 
      x = d.width - XSIZE; 
      dx = -dx; 
    }
    if (y < 0)
    { 
      y = 0; 
      dy = -dy; 
    }
    if (y + YSIZE >= d.height)
    { 
      y = d.height - YSIZE; 
      dy = -dy; 
    }
    g.fillOval(x, y, XSIZE, YSIZE);
    g.dispose();
  }
  
  public void bounce()
  {
    draw();
    for (int i = 1; i <= 1000; i++)
    {  
      move();
      try
      { 
       Thread.sleep(5); 
      }
      catch(InterruptedException e)
      {}
    }
  }
  
  private JPanel box;
  private static final int XSIZE = 10;
  private static final int YSIZE = 10;
  private int x = 0;
  private int y = 0;
  private int dx = 2;
  private int dy = 2;
}