Sun Java Solaris Communities My SDN Account Join SDN
 
Tutorials & Code Camps

Beeping Mouse

 
Training Index

Beeping Mouse

by jGuru

Help  API Docs  About This Short Course  Short Course  Exercises

This exercise introduces delegation-based event handling. The skeleton currently sets the background color to pink (so that the applet's area within the browser window is identifiable). The objective of this exercise is to enhance the applet so that it issues a beep every time a mouse button is clicked in the applet's area of the browser window. (A mouse click is a mouse button press followed by a mouse button release, without moving the mouse.)

Skeleton Code

Tasks

1. The delegation-based event handling classes are in the java.awt.event package. Import the entire contents of this package.
2.

The applet will be the event source--this functionality already exists. For a simple task such as beeping when a mouse button is clicked, it's convenient to design the applet to function as the event target as well. With this design, one class (MouseBeep) does everything.

In order to function as a target for mouse button events, the applet (class) must implement the MouseListener interface and provide implementations for all of the methods in the interface. The next task is to add this functionality; for now, each prescribed method should have an empty body (the method does nothing).

3.

With these methods, the applet can now function as an event target. Note, however, that event targets must register with event sources. (In this case, the source and the target are the same, but, nevertheless, the source must have a list of who to propagate events to, even if the "who" is itself.) Therefore, the next task is to register the applet as an event target for mouse events.

4. The final task is to add the functionality to issue a beep whenever there is a mouse click. The source (the current applet) will automatically invoke the target's (the current applet) mouseClicked() method when there is a mouse click. Thus, the final task is to add this functionality to the currently empty mouseClicked() method.

Where help exists, the task numbers above are linked to the step-by-step help page.

Solution Source

Demonstration

This exercise only runs within browsers that support the Java Runtime Environment 1.1 and appletviewer. If you are using an appropriate browser, try this exercise. There is no output, other than the window area allocated to the applet. The background color is set to pink so that the applet area is identifiable:

mousebeep.gif

Next Exercise

Exercises

Short Course

Copyright 1996-2000 jGuru.com. All Rights Reserved.