// SpriteDemoMIDlet.java (c) Kari Laitinen // http://www.naturalprogramming.com/ // 2009-09-29 File created. // 2011-04-28 Last modification. /* This midlet demonstrates: - animation - use of the Sprite class */ import java.io.* ; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.lcdui.game.Sprite ; class SpriteDemoCanvas extends Canvas implements Runnable { Thread animation_thread ; boolean thread_must_be_run = false ; int canvas_width = getWidth() ; int canvas_height = getHeight() ; Image picture_for_sprite ; Sprite demo_sprite ; int picture_width, picture_height ; int sprite_frame_width, sprite_frame_height ; public SpriteDemoCanvas() { try { picture_for_sprite = Image.createImage( "/four_orange_arrow_frames.png" ) ; picture_width = picture_for_sprite.getWidth() ; picture_height = picture_for_sprite.getHeight() ; sprite_frame_width = picture_width / 4 ; sprite_frame_height = picture_height ; demo_sprite = new Sprite( picture_for_sprite, sprite_frame_width, sprite_frame_height ) ; } catch ( IOException io_exception ) { System.out.print( "\n Could not create an Image object .... " ) ; } } public synchronized void start_animation_thread() { if ( animation_thread == null ) { animation_thread = new Thread( this ) ; thread_must_be_run = true ; animation_thread.start() ; } } public void stop_animation_thread() { if ( animation_thread != null ) { thread_must_be_run = false ; animation_thread.interrupt() ; animation_thread = null ; } } public void run() { while ( thread_must_be_run == true ) { repaint() ; try { Thread.sleep( 2000 ) ; } catch ( InterruptedException caught_exception ) { // No actions to handle the exception. } } } protected void paint( Graphics graphics ) { // The background color is red graphics.setColor( 255, 0, 0 ) ; graphics.fillRect( 0, 0, canvas_width, canvas_height ) ; demo_sprite.nextFrame() ; demo_sprite.paint( graphics ) ; } } public class SpriteDemoMIDlet extends MIDlet { Display midlet_display = Display.getDisplay( this ) ; SpriteDemoCanvas sprite_demo_canvas = new SpriteDemoCanvas() ; protected void startApp() throws MIDletStateChangeException { midlet_display.setCurrent( sprite_demo_canvas ) ; sprite_demo_canvas.start_animation_thread() ; } protected void pauseApp() { sprite_demo_canvas.stop_animation_thread() ; } protected void destroyApp( boolean unconditional_destruction_required ) { sprite_demo_canvas.stop_animation_thread() ; } }