import java.applet.Applet; import java.util.Enumeration; import java.awt.Graphics; import java.awt.Dimension; import java.awt.Event; import java.awt.Color; public class BabblerApplet extends Applet implements Runnable { /* An applet that writes a string directly into any sibling applet's window. */ private Thread thread; private String name; private Dimension size; private final static int SLEEP_TIME = 2000; //in milliseconds private final static int WINDOW_SIZE = 210; //in pixels private final static int OFFSET = 5; //in pixels public void init() { name = this.getParameter("BabblerName"); this.resize(WINDOW_SIZE, WINDOW_SIZE); size = this.getSize(); this.setBackground(Color.white); } public void start() { if (thread == null) { thread = new Thread(this); thread.start(); } } public void stop() { thread = null; } public void run() { /* Repeatedly find all current siblings and write a string in their windows. */ while (thread != null) { Enumeration applets = this.getAppletContext().getApplets(); while (applets.hasMoreElements()) { Applet applet = (Applet) (applets.nextElement()); String itsName = applet.getParameter("BabblerName"); boolean isOther = (applet != this); boolean isSibling = (itsName != null); if (isOther && isSibling) { int place = 5 * OFFSET + (int) (Math.random() * (size.height - OFFSET)); Graphics graphics = applet.getGraphics(); graphics.drawString(name + " calling " + itsName, 0, place); } } try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException exception) { System.out.println("interrupted"); } } } public void paint(Graphics graphics) { graphics.drawRect(0, 0, size.width - OFFSET, size.height - OFFSET); graphics.drawString("Name: " + name, 0, 4 * OFFSET); } public boolean mouseDown(Event event, int x, int y) { /* Stop this applet if the user clicks in its window. */ stop(); return false; } public boolean mouseEnter(Event event, int x, int y) { /* Clean this applet if the user moves over its window. */ repaint(); return false; } }