// Bugs.java // Solution to CS 5 Lab Assignment #2 by THC. // This applet puts up a window with a pink background. // Wherever you double-click, a bug appears and moves toward the top // of the applet window. // If you single-click over any part of a bug, it disappears. // If the location of a single-click is over more than one bug, then // all the bugs at the click location disappear. // The action stops when the mouse leaves the applet window, and it // resumes when the mouse enters the applet window. import java.applet.Applet; import java.awt.*; import java.awt.event.*; import javax.swing.Timer; public class Bugs extends Applet implements ActionListener, MouseListener { private final int APPLET_WIDTH = 500, APPLET_HEIGHT = 500; private final int MAXBUGS = 500; // max number of Bugs we can have at once private Timer timer; // a Timer for when the Bugs move up private Swarm infestation; // maintains information about all existing Bugs // Initialize the applet. public void init() { final int DELAY = 100; // how long between Timer events setSize(APPLET_WIDTH, APPLET_HEIGHT); // set the window size setBackground(Color.pink); // use a pink background // Because we draw every Bug the same, it's most efficient to // tell the Bug class what image to draw and what applet will // be displaying the image. Bug.init(getImage(getCodeBase(), "bug0.gif"), this); // Create a Swarm object, initially with no Bugs. infestation = new Swarm(MAXBUGS); // Create the Timer and make this applet listen for Timer and mouse events. timer = new Timer(DELAY, this); timer.start(); addMouseListener(this); // Display an empty window. repaint(); } // To draw the applet window, draw all the existing Bugs and a string saying // how many Bugs there are right now. public void paint(Graphics page) { infestation.draw(page); page.setColor(Color.black); page.drawString("Bugs: " + infestation.getBugCount(), 10, APPLET_HEIGHT-10); } // When the Timer rings, move all the Bugs and redisplay the window. public void actionPerformed(ActionEvent event) { infestation.move(); repaint(); } // Handle a mouse click event. // If a single-click, hit all Bugs at the location of the click, terminating them. // If a double-click, add a new Bug at the location of the click. public void mouseClicked(MouseEvent event) { int clicks = event.getClickCount(); // how many clicks? Point where = event.getPoint(); // where is the mouse? if (clicks == 1) infestation.hitBugs(where); // single-click: hit Bugs else if (clicks == 2) infestation.add(where); // double-click: add a new Bug } // Start the Timer when the mouse enters the window. public void mouseEntered(MouseEvent event) { timer.start(); } // Stop the Timer when the mouse exits the window. public void mouseExited(MouseEvent event) { timer.stop(); } // Empty defintions for unused mouse events. public void mousePressed(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} }