
450
|
Chapter 12, Miscellany
#90 Create Demonstrations with the Robot Class
HACK
H A C K
#90
Create Demonstrations with the Robot Class
Hack #90
Use the Robot class to control the mouse cursor and create interactive
software features.
One of the coolest things about Swing is that you can often use a class for
something completely different than what it was originally intended. The
java.awt.Robot class, for example, can move the mouse cursor programmat-
ically. This feature was originally intended for use by automated testing
tools (hence the name Robot), but I’ve found it very useful to demonstrate
software features by moving the mouse cursor through the same actions as
the user. Instead of just describing something in a help file, you can actually
show the user what to do—and this hack explains how.
I, Robot
To create a mouse animation, you need three things:
1. The ability to move the cursor
2. The start and end points of the animation
3. A way to smoothly interpolate the cursor position
The
java.awt.Robot class has a variety of methods for capturing program
state and controlling the user interface, including
Robot.mouseMove( ), which
allows you to move the mouse cursor programmatically.
The following code is the implementation of a method
moveMouse( ), which
takes three arguments: a starting component, an ending component, and a
duration for the animation (in milliseconds). Because most demonstrations
involve ...