import java.applet.Applet; import java.awt.*; import java.util.*; public class SingleThreadApplet extends Applet { Button createButton = new Button("new thread"); Button startButton = new Button("start thread"); Button stopButton = new Button("stop thread"); Box box = new Box(40, 40, 300, 300, Color.black); Ball ball = null; public void init () { add(createButton); add(startButton); add(stopButton); } public void stop() { if (ball != null) { ball.stop(); ball = null; } } public boolean action (Event evt, Object arg) { if (evt.target == createButton) { if (ball == null ) // if there is NO thread ball = new Ball(this, 100, 100, 4, 7, box, Color.red); // create the thread } else if (evt.target == startButton) { if (ball != null && !ball.isAlive()) // if there is a thread and it is NOT running ball.start(); // start the thread } else if (evt.target == stopButton) { if (ball != null ) { // if there is a thread ball.stop(); // stop the thread ball = null; } } repaint(); return true; } // double buffering of the graphics Dimension offDimension; Image offImage; Graphics offGraphics; public void update(Graphics g) { Dimension d = size(); // Create the offscreen graphics context if ((offGraphics == null) || (d.width != offDimension.width) || (d.height != offDimension.height)) { offDimension = d; offImage = createImage(d.width, d.height); offGraphics = offImage.getGraphics(); } // Erase the previous image offGraphics.setColor(getBackground()); offGraphics.fillRect(0, 0, d.width, d.height); // draw the shapes into the image if (ball != null) ball.draw(offGraphics); box.draw(offGraphics); // Paint the image onto the screen g.drawImage(offImage, 0, 0, null); } public void paint(Graphics g) { update(g); } }