Example -- Applet with mouse drag events
In this example, the applet implements the MouseMotionListener
interface. This applet demonstrates the mouse events when the mouse is
pressed and dragged within the applet. The applet also has a Refresh
button and hence implements the ActionListener interface to handle
the button click event.
Listing 2.1.5 shows the source code for the above program.
Position the mouse within the applet. Now press the left mouse and drag the mouse within the applet.
As the mouse is dragged, the events are handled by the mouseDragged method. The MouseEvent object passed
to this method is used to obtain the current location of the mouse, i.e., the (x,y) coordinates of the mouse relative
to the applet. A small filled oval is displayed at each mouse location. Try drawing "Java" in the applet. The
Refresh button is used to refresh the applet. In contrast to the
earlier examples, the repaint method is not called within the event
handling method after each mouse event occurs. The repaint method
call would only draw whatever the code written in the paint method.
In our example, the paint method only draws the fill at the current
location, and has no means to remember all the previous locations where
the mouse has been dragged. Hence, the repaint method invocation is
purposefully omitted in the mouseDragged method. The MouseMotionListener
requires the mouseMoved method also to be implemented. In this applet, we
don't have anything to do when the mouse is simply moved within the
applet. Hence the method is declared but no code is provided. The method
is called anyway when the mouse is moved within the applet.
|