import java.awt.*; public class Graph2 extends java.applet.Applet implements Runnable { int step = 0; Thread mainThread; // An offscreen image Image offscreen; boolean pause = false; public void init() { // Create the offscreen image offscreen = createImage(360, 180); // Clear it Graphics g = offscreen.getGraphics(); clearImage(g); // Now create a thread for the action to happen in mainThread = new Thread(this); mainThread.start(); } public void update(Graphics g) { paint(g); } synchronized public void paint(Graphics g) { // Just copy the offscreen image to the screen. g.drawImage(offscreen, 0, 0, this); } synchronized void drawCurrentStep() { // Get a "pen" for our offscreen image Graphics g = offscreen.getGraphics(); // Clear the image clearImage(g); // Set the drawing color for the curve g.setColor(Color.red); int x; // Use this to remember the last position so we // can draw a line back to it. We have to give it // an initial value or the compiler will complain. int oldy = 0; // Trig refresher course! for (x = 0; (x < 360); x += 4) { double degrees = x + step; // Convert degrees to radians double radians = degrees * .0174532925; int y = (int) (Math.sin(radians) * 90) + 90; // Draw a red line from this value to the previous one, // if any if (x > 0) { g.drawLine(x - 4, oldy, x, y); } // Remember this position for the next line oldy = y; } } public void run() { while (true) { if (pause) { // Sleep a lot when paused try { mainThread.sleep(100); } catch (Exception e) { // Nothing will be interrupting us, // so just catch and do nothing here } } else { // Move and draw moveOneStep(); drawCurrentStep(); repaint(); } } } void moveOneStep() { step++; if (step == 360) { step = 0; } try { mainThread.sleep(50); } catch (Exception e) { // Nothing will be interrupting us, // so just catch and do nothing here } } void clearImage(Graphics g) { // Clear the image g.setColor(Color.black); g.fillRect(0, 0, 360, 180); } public void start() { // This is called by the browser // when the user returns to this // web page, and also once right // after init(). Clear the // pause flag. pause = false; } public void stop() { // This is called by the browser // when the user leaves this // web page. Set the pause flag // to avoid wasting CPU. pause = true; } public void destroy() { // This is called by the browser // when the web page is being // thrown out of cache and the // applet is discarded. It is our // task to stop our thread. mainThread.stop(); } };