import java.awt.*; import java.awt.event.*; /** A simple Java program to demonstrate graphics, threads, and animation **/ class AnimationDemo extends Canvas implements Runnable { int canvasWidth = 400; // all values in pixels int textWidth = 100; int textHeight = 20; int x = canvasWidth; // start text near top-right corner int y = textHeight; boolean running = false; Button startButton; DoubleScroller delayScroll; // constructor method to initialize the simulation: AnimationDemo() { Frame myFrame = new Frame("Animation!"); // create a window Panel topPanel = new Panel(); // top panel holds canvas myFrame.add(topPanel); topPanel.add(this); this.setSize(canvasWidth,canvasWidth); Panel bottomPanel = new Panel(); // bottom panel holds controls myFrame.add(bottomPanel,BorderLayout.SOUTH); startButton = new Button("Start"); bottomPanel.add(startButton); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { running = !running; if (running) startButton.setLabel("Stop"); else startButton.setLabel("Start"); }}); delayScroll = new DoubleScroller(" Delay in ms = ",1,100,1,20); bottomPanel.add(delayScroll); myFrame.setResizable(false); myFrame.pack(); // make the window just big enough myFrame.setVisible(true); Thread myThread = new Thread(this); // create the simulation thread myThread.start(); } // run method, called by the calculation thread: public void run() { while (true) { if (running) { x -= 1; // move one pixel to the left if (x < -textWidth) { // if we're off the left edge... x = canvasWidth; y += textHeight; if (y > canvasWidth) { y = textHeight; } } repaint(); // tell Java to call the paint method } int delay = (int) delayScroll.getValue(); try {Thread.sleep(delay);} catch (InterruptedException e) {} } } // Java calls this method whenever the canvas needs to be drawn: public void paint(Graphics g) { g.drawString("Hello, world!",x,y); } // boring main method to get things started: public static void main(String[] arg) { new AnimationDemo(); } }