/** * Creates a thread that run a cycle of red, green, yellow, red, etc. * lights on a traffic light. Adds buttons to stop and start the * animation. This is in the file "example-progs/buttons/TLApplet.java" */ import java.applet.*; // for Class Applet import java.awt.*; // for Color public class TLApplet extends Applet implements Runnable { TrafficLight trafficLight = new TrafficLight( Color.green ); Thread tlThread = null; Button stop,start; // Buttons to stop and start animation public void init() // Applet method { System.out.println("TLApplet's init() method called"); setLayout( new BorderLayout() ); add( "Center", trafficLight ); stop = new Button( "Stop" ); // Create button with Stop label add( "West", stop ); // Add it to the applet start = new Button( "Start" ); // Create button w Start label add( "East", start ); // and add to applet tlThread = new Thread( this ); // Give thread a runnable object tlThread.start(); // Start thread running } public void start() // Applet method { System.out.println("TLApplet's start() method called"); tlThread.resume(); // First time resume called on already start.disable(); stop.enable(); } // started thread, but this causes no // problem public void stop() // Applet method { System.out.println("TLApplet's stop() method called"); tlThread.suspend(); // Suspend thread when Applet is stopped. start.enable(); stop.disable(); } public void destroy() // Applet method { System.out.println("TLApplet's destroy() method called"); tlThread.stop(); // Stop thread when Applet is terminated. tlThread = null; } public static void main( String arg[] ){ Frame f = new Frame( "TL w Buttons" ); TLApplet tl = new TLApplet(); f.setSize(300,600); f.add("Center",tl); tl.init(); f.show(); tl.start(); } public void run() // Thread method { System.out.println("Entering TLApplet:run()"); while ( true ) { trafficLight.setColor( Color.red ); // Change traffic light to red try{ Thread.sleep(10000); } catch ( InterruptedException e ) {} trafficLight.setColor( Color.green ); // Change traffic light to green try{ Thread.sleep(10000); } catch ( InterruptedException e ) {} trafficLight.setColor( Color.yellow );// Change traffic light to yellow try{ Thread.sleep(5000); } catch ( InterruptedException e ) {} } } // Event handler for buttons public boolean action( Event e, Object arg ){ if ( e.target == stop ){ System.out.println( "Processing stop button" ); tlThread.suspend(); // Suspend animation start.enable(); // Enable start button stop.disable(); // Disable stop button return true; } if ( e.target == start ){ System.out.println( "Processing start button" ); tlThread.resume(); start.disable(); stop.enable(); return true; } return super.action( e,arg ); } }