/* This Applet demonstrates how to handle MouseEvents in an Applet using the Java 1.1 event model. The applet just moves a circle around the screen, centering it on the mouse whenever the user clicks the mouse button. Note that this same technique can be applied to other components, such as subclasses of Canvas as well. Author: Jeremy Baer */ // import some packages we will need import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class MouseExampleApplet extends Applet implements MouseListener { // private instance variables to hold the current center coords // of the circle private int circleX = 100, circleY = 100; ///////////////////////////////////////////////////////////////// // init ///////////////////////////////////////////////////////////////// /** * This method is called by the browser or appletviewer directly * after the applet has been instantiated and directly before * it starts running. Here we simply add this applet as * an MouseListener for itself. * * @return None */////////////////////////////////////////////////////////////// public void init() { // this works because the applet implements MouseListener addMouseListener(this); } ///////////////////////////////////////////////////////////////// // paint ///////////////////////////////////////////////////////////////// /** * This method is used to draw the contents of the applet. * It simply draws a circle centered at the current circle x and * y coordinates. * * @param Graphics The on-screen graphics context for * the applet. * * @return None */////////////////////////////////////////////////////////////// public void paint(Graphics g) { // draw the circle g.fillOval(circleX - 20, circleY - 20, 40, 40); } ///////////////////////////////////////////////////////////////// // mousePressed ///////////////////////////////////////////////////////////////// /** * This method is declared abstractly in the MouseListener * interface, and is required in order for the applet to * implement that interface. It is used here to process mouse * clicks and change the location of the circle the applet draws. * * @param MouseEvent A mouse event for us to handle. * * @return None */////////////////////////////////////////////////////////////// public void mousePressed(MouseEvent evt) { // grab the current mouse coordinates from the MouseEvent int x = evt.getX(); int y = evt.getY(); // update the circle coordinates and redraw circleX = x; circleY = y; repaint(); } ////////////////////////////////////////////////////////////////// // // The following methods are required in order to complete the // implementation of the MouseListener interface, even though // in this applet they are "do-nothing" methods. // ////////////////////////////////////////////////////////////////// public void mouseReleased(MouseEvent evt) { } public void mouseClicked(MouseEvent evt) { } public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { } }