// PacmanApplet.java Copyright (c) Kari Laitinen // http://www.naturalprogramming.com/ // 2007-09-26 This file was created. // 2009-11-18 Last modification // This applet displays a "Pacman" whose mouth opens and closes // constantly. This is thus yet another example of simple animation. import java.awt.* ; import javax.swing.* ; class PacmanPanel extends JPanel implements Runnable { Thread animation_thread = null ; boolean thread_must_be_executed = false ; int[] pacman_mouth_angles = { 90, 75, 60, 45, 30, 15, 0, 15, 30, 45, 60, 75 } ; int mouth_angle_index = 0 ; public PacmanPanel() { setBackground( new Color( 255, 255, 110 ) ) ; // light yellow } public void start_animation_thread() { if ( animation_thread == null ) { animation_thread = new Thread( this ) ; thread_must_be_executed = true ; animation_thread.start() ; } } public void stop_animation_thread() { if ( animation_thread != null ) { animation_thread.interrupt() ; thread_must_be_executed = false ; animation_thread = null ; } } public void run() { while ( thread_must_be_executed == true ) { try { Thread.sleep( 50 ) ; } catch ( InterruptedException caught_exception ) { thread_must_be_executed = false ; } mouth_angle_index ++ ; if ( mouth_angle_index >= pacman_mouth_angles.length ) { mouth_angle_index = 0 ; } repaint() ; } } public void paintComponent( Graphics graphics ) { super.paintComponent( graphics ) ; int pacman_position_x = getSize().width / 2 - 60 ; int pacman_position_y = getSize().height / 2 - 50 ; int pacman_mouth_angle = pacman_mouth_angles[ mouth_angle_index ] ; graphics.fillArc( pacman_position_x, pacman_position_y, 120, 100, pacman_mouth_angle / 2, 360 - pacman_mouth_angle ) ; } } public class PacmanApplet extends JApplet { PacmanPanel pacman_panel ; public void init() { pacman_panel = new PacmanPanel() ; getContentPane().add( pacman_panel ) ; } public void start() { pacman_panel.start_animation_thread() ; } public void stop() { pacman_panel.stop_animation_thread() ; } }