// WormApplet.java (c) 2002-2006 Kari Laitinen // http://www.naturalprogramming.com/ // 2006-10-06 File created. // 2006-10-19 Last modification. // This program is an example related to animation and the use // of threads. // A problem of this program is that the worm that moves on the // screen flickers sometimes. The cause of this is that the screen // is updated so often. // When this applet is implemented as a JPanel-based applet // (see WormPanelApplet.java) there is no flickering of the screen // because the JPanel class provides an automatic double buffering // of the screen image. // To find out what double buffering means, please study the program // WormOffscreenApplet.java which is yet another version of this program. import java.awt.* ; import java.util.* ; import javax.swing.* ; public class WormApplet extends JApplet implements Runnable { Thread animation_thread ; boolean thread_must_be_executed = false ; Color worm_color = Color.red ; int worm_position_x ; int worm_position_y = 150 ; int worm_length = 100 ; int worm_height = 30 ; int applet_width, applet_height ; public void init() { applet_width = getSize().width ; applet_height = getSize().height ; } public void start() { if ( animation_thread == null ) { animation_thread = new Thread( this ) ; thread_must_be_executed = true ; animation_thread.start() ; } } public void stop() { if ( animation_thread != null ) { animation_thread.interrupt() ; thread_must_be_executed = false ; animation_thread = null ; } } public void run() { while ( thread_must_be_executed == true ) { worm_position_x = 50 ; worm_length = 100 ; repaint() ; let_this_thread_sleep( 2000 ) ; while ( worm_position_x + worm_length < applet_width && thread_must_be_executed == true ) { for ( int stretchings_counter = 0 ; stretchings_counter < 7 ; stretchings_counter ++ ) { worm_length = worm_length + 5 ; repaint() ; let_this_thread_sleep( 50 ) ; } for ( int shrinkings_counter = 0 ; shrinkings_counter < 7 ; shrinkings_counter ++ ) { worm_length = worm_length - 5 ; worm_position_x = worm_position_x + 5 ; repaint() ; let_this_thread_sleep( 50 ) ; } } let_this_thread_sleep( 4000 ) ; } } void let_this_thread_sleep( int given_sleeping_time_in_milliseconds ) { // We won't let the thread sleep if it is supposed to die. // Without the following if construct the 'behavior' of the // worm is somewhat unpredictable in certain situations when // the applet window is minimized and 'un-minimized'. if ( thread_must_be_executed == true ) { try { Thread.sleep( given_sleeping_time_in_milliseconds ) ; } catch ( InterruptedException caught_exception ) { } } } public void paint( Graphics graphics ) { super.paint( graphics ) ; graphics.setColor( worm_color ) ; graphics.fillRoundRect( worm_position_x, worm_position_y, worm_length, worm_height, 20, 20 ) ; } }