/home/wpollock1/public_html/Java/HoopsApp.java
// Display some bouncing hoops. This more complex
// applet version eliminates the "flicker" of the text.
// Written by Wayne Pollock, Tampa, FL USA, 1999
// Modified 2002 to stop a Thread the safe way.
// Modified 2011 to use the applet's actual width; the
// "-4" accounts for a 4 pixel border around the edge
// of the applet.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class HoopsApp extends Applet implements Runnable
{
int appletWidth;
int hoopDiameter = 40;
int dir = 1; // "1" for forward, "-1" for backward.
int hoop1_pos;
int hoop2_pos;
volatile Thread t; // must be volitile to prevent memory consistency errors
public void init ()
{
appletWidth = getWidth();
hoop1_pos = 4;
hoop2_pos = appletWidth - 4 - hoopDiameter;
setBackground( Color.cyan );
setLayout( null );
Label myLabel = new Label( "Bouncing Hoops!" );
myLabel.setFont( new Font( "SansSerif", Font.BOLD, 24 ) );
myLabel.setBounds( new Rectangle( 60, 160, 200, 30 ) );
add( myLabel );
}
public void start () // Applet's start method, not Thread's.
{
t = new Thread( this );
t.start(); // Starts the animation.
}
public void stop ()
{
//t.stop(); // Thread.stop is very dangerous and is no longer used.
t = null;
}
public void run ()
{
for ( ;; )
{ try
{ Thread.sleep( 30 );
} catch ( InterruptedException ie ) {}
if ( t == null ) // if so, stop() was called.
break;
repaint();
}
}
public void update( Graphics g )
{
paint( g );
}
public void paint ( Graphics g )
{
// Erase previous hoops:
g.setColor( Color.cyan );
g.drawOval( hoop1_pos, 60, hoopDiameter, hoopDiameter );
g.drawOval( hoop2_pos, 60, hoopDiameter, hoopDiameter );
// Draw the hoops in their new positions:
if ( hoop1_pos >= ((appletWidth/2) - hoopDiameter - 1)
|| hoop1_pos < 4 )
dir = -dir;
hoop1_pos += dir * 3;
hoop2_pos -= dir * 3;
g.setColor( Color.red );
g.drawOval( hoop1_pos, 60, hoopDiameter, hoopDiameter );
g.setColor( Color.blue );
g.drawOval( hoop2_pos, 60, hoopDiameter, hoopDiameter );
}
}