Enable the Image to Handle Mouse Clicks
In order to enable the image to respond to mouse events, you need to do two things:
Tell your applet to respond to mouse events
Write the event handler code for mouse events
The first part is simple. Just call addMouseListener at the end of your
init() method. This tells the applet that mouse events should be acknowledged, and that your class will process them.
To write the event handler, your class must implement the MouseListener interface. You can then write a
processMouseEvent() method by which you simply save the X and Y coordinates where the user clicks and set a flag called doimg that says the image should appear on the screen. Finally, the event handler uses
repaint() to tell the applet to refresh its screen (because the user has clicked the mouse at a specific coordinate and you want the picture to appear at that coordinate).
The applet also needs to define code for all the other methods defined by the MouseListener interface, namely
mouseExited(). However, because you don't need the applet to respond to these events, you can leave their implementation empty.
Next, comes the
paint() method. Like
init(), it is defined by the java.applet.Applet class (from which your applet is derived) and is called automatically whenever it is needed. The times it's needed include when the window first appears on the screen and when another window partially or completely occludes the applet window and then moves away. You can also explicitly force a call to the
paint() method by using the applet's
repaint() method as you do in your mouse event handler.
Paint() is called with a Graphics context g as its argument. You can now use a number of methods in the Graphics class to alter the drawing area. Begin by determining the current size of the applet's drawing area via a call to
getSize(), which returns a Dimension object containing the height and width properties. Then use the drawRect method of the Graphics class to draw a blank rectangle that covers the entire drawing areathis is simply a quick-and-dirty way to clear your drawing area, so you don't ghost your images when you move the mouse around.
Next, invite the user to click anywhere. If the class variable doimg is true and the class variable imgnam is not null, then the image retrieved during the
init() method will be displayed, followed by the message "Squeak!" in red.
The method call
img.getHeight(this) returns the height of the image. Use the height to calculate the y coordinate of the "Squeak!" string, so that it appears just below your image.