import java.applet.Applet; import java.awt.*; import java.util.*; public class BlinkingObjectsApplet extends Applet { Vector objects = new Vector(); // double buffering to avoid flashing Dimension offDimension; Image offImage; Graphics offGraphics; public void init() { add(new Button("new object")); newObject(this); } public void start() { Enumeration e = objects.elements(); Blinkable obj; while (e.hasMoreElements()) { // step through all vector elements obj = (Blinkable) e.nextElement(); obj.startBlinking(); } } public void stop() { Enumeration e = objects.elements(); Blinkable obj; while (e.hasMoreElements()) { // step through all vector elements obj = (Blinkable) e.nextElement(); obj.stopBlinking(); } } public boolean action(Event e, Object arg) { newObject(this); repaint(); return(true); } public void paint(Graphics g) { update(g); } public void update(Graphics g) { Dimension d = size(); 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); //Rebuild the image. offGraphics.setColor(Color.black); Enumeration e = objects.elements(); Blinkable obj; while (e.hasMoreElements()) { // step through all vector elements obj = (Blinkable) e.nextElement(); obj.draw(offGraphics); } //Paint the image onto the screen. g.drawImage(offImage, 0, 0, this); } void newObject(Applet applet) { BlinkingCharacter c; BlinkingShape s; if (0 == (int) Math.round(Math.random())) { // character if (0 == (int) Math.round(Math.random())) { c = new BlinkingLetter(applet); } else { c = new BlinkingDigit(applet); } c.randomize(); // choose random properties of character c.startBlinking(); objects.addElement(c); } else { // shape if (0 == (int) Math.round(Math.random())) { s = new BlinkingOval(applet); } else { s = new BlinkingRectangle(applet); } s.randomize(); // choose random properties of character s.startBlinking(); objects.addElement(s); } } }