HoopsApp.java

Download HoopsApp.java

 1: // Display some bouncing hoops.  This more complex
 2: // applet version eliminates the "flicker" of the text.
 3: // Written by Wayne Pollock, Tampa, FL USA, 1999
 4: // Modified 2002 to stop a Thread the safe way.
 5: // Modified 2011 to use the applet's actual width; the
 6: //   "-4" accounts for a 4 pixel border around the edge
 7: //   of the applet.
 8: 
 9: import java.applet.*;
10: import java.awt.*;
11: import java.awt.event.*;
12: 
13: public class HoopsApp extends Applet implements Runnable
14: {
15:    int appletWidth;
16:    int hoopDiameter = 40;
17:    int dir = 1;  // "1" for forward, "-1" for backward.
18:    int hoop1_pos;
19:    int hoop2_pos;
20:    volatile Thread t;  // must be volitile to prevent memory consistency errors
21: 
22:    public void init ()
23:    {
24:       appletWidth  = getWidth();
25:       hoop1_pos = 4;
26:       hoop2_pos = appletWidth - 4 - hoopDiameter;
27:       setBackground( Color.cyan );
28:       setLayout( null );
29:       Label myLabel = new Label( "Bouncing Hoops!" );
30:       myLabel.setFont( new Font( "SansSerif", Font.BOLD, 24 ) );
31:       myLabel.setBounds( new Rectangle( 60, 160, 200, 30 ) );
32:       add( myLabel );
33:    }
34: 
35:    public void start ()   // Applet's start method, not Thread's.
36:    {
37:       t = new Thread( this );
38:       t.start();            // Starts the animation.
39:    }
40: 
41:    public void stop ()
42:    {
43:       //t.stop(); // Thread.stop is very dangerous and is no longer used.
44:       t = null;
45:    }
46: 
47:    public void run ()
48:    {
49:       for ( ;; )
50:       {  try
51:          {  Thread.sleep( 30 );
52:          } catch ( InterruptedException ie ) {}
53: 
54:          if ( t == null )  // if so, stop() was called.
55:             break;
56:          repaint();
57:       }
58:    }
59: 
60:    public void update( Graphics g )
61:    {
62:       paint( g );
63:    }
64: 
65:    public void paint ( Graphics g )
66:    {
67:       // Erase previous hoops:
68:       g.setColor( Color.cyan );
69:       g.drawOval( hoop1_pos, 60, hoopDiameter, hoopDiameter );
70:       g.drawOval( hoop2_pos, 60, hoopDiameter, hoopDiameter );
71: 
72:       // Draw the hoops in their new positions:
73:       if ( hoop1_pos >= ((appletWidth/2) - hoopDiameter - 1)
74:            || hoop1_pos < 4 )
75:          dir = -dir;
76:       hoop1_pos += dir * 3;
77:       hoop2_pos -= dir * 3;
78:       g.setColor( Color.red );
79:       g.drawOval( hoop1_pos, 60, hoopDiameter, hoopDiameter );
80:       g.setColor( Color.blue );
81:       g.drawOval( hoop2_pos, 60, hoopDiameter, hoopDiameter );
82:    }
83: }