import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.*; /* This is just like LineApplet, but there is a way to slow down the action. There is a speed control that affects the delay after each command is processed. A separate "animation thread" processes the commands and waits after each one. When the user clicks on the Go button, any text in the textarea is processed. Each TimedLine of text is assumed to represent a command to draw a line on the TimedLineCanvas component of the applet. Example input: LINE (100,100) (500,150) LINE (100,300) (500,250) LINE 100 100 100 300 Written by Steve Tanimoto, January 2001. */ public class TimedLineApplet extends Applet implements ActionListener, Runnable { TextArea ta; TimedLineCanvas theTimedLineCanvas; Button goButton; Thread animationThread; int millisecDelay = 500; Valuator speedControl; int x1, y1, x2, y2; public void init() { setLayout(new BorderLayout()); ta = new TextArea(5,20); theTimedLineCanvas = new TimedLineCanvas(); goButton = new Button("Go"); theTimedLineCanvas.setSize(300,200); theTimedLineCanvas.setBackground(Color.gray); speedControl = new Valuator("Millisec Delay", 500, 2000, Color.gray); add(ta, BorderLayout.NORTH); add(theTimedLineCanvas, BorderLayout.CENTER); add(goButton, BorderLayout.SOUTH); add(speedControl, BorderLayout.EAST); goButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == goButton) { startAnimation(); } } int inputInt; boolean isInt(String token) { boolean returnVal = true; try { inputInt = (new Integer(token)).intValue(); } catch(NumberFormatException nfe) { error("TimedLineApplet expected an integer but found: " + token); returnVal = false; } return returnVal; } void error(String msg) { theTimedLineCanvas.setString(msg); System.out.println(msg); } void startAnimation() { animationThread = new Thread(this); animationThread.start(); } public void run() { theTimedLineCanvas.clear(); StringTokenizer lines = new StringTokenizer(ta.getText(), "\n"); while (lines.hasMoreTokens()) { String line = lines.nextToken(); millisecDelay = speedControl.getValue(); try { StringTokenizer lt = new StringTokenizer(line, "() ,;"); String command = lt.nextToken(); if (command.equals("CLEAR")) { theTimedLineCanvas.clear(); continue; } if (! (command.equals("LINE"))) { error("Unknown command: " + command); continue; } if (isInt(lt.nextToken())) { x1 = inputInt; } else continue; if (isInt(lt.nextToken())) { y1 = inputInt; } else continue; if (isInt(lt.nextToken())) { x2 = inputInt; } else continue; if (isInt(lt.nextToken())) { y2 = inputInt; } else continue; theTimedLineCanvas.addLine(x1, y1, x2, y2); try { animationThread.sleep(millisecDelay); } catch(InterruptedException ie) {} } catch (Exception exc) { error("TimedLineApplet expected a proper LINE command but got: " + line); } } } }