
288
|
Chapter 8, Rendering
#56 Create a Magnifying Glass Component
HACK
Build the Magnifying Glass
The DetachedMagnifyingGlass will need to keep track of the Component it’s
viewing, the current mouse location in that component, a zoom factor, and
its own size. It will also need an instance of the AWT
Robot
for taking screen
grabs. The other thing it needs to do is to have a
MouseMotionListener
, so
that it will get updates on the cursor’s position and, when it changes, do a
new grab and
repaint( )
.
The
DetachedMagnifyingGlass code is shown in Example 8-1.
Example 8-1. JComponent to provide a magnified view of another JComponent
public class DetachedMagnifyingGlass extends JComponent
implements MouseMotionListener {
double zoom;
JComponent comp;
Point point;
Dimension mySize;
Robot robot;
public DetachedMagnifyingGlass (JComponent comp,
Dimension size,
double zoom) {
this.comp = comp;
// flag to say don't draw until we get a MouseMotionEvent
point = new Point (-1, -1);
comp.addMouseMotionListener(this);
this.mySize = size;
this.zoom = zoom;
// if we can't get a robot, then we just never
// paint anything
try {
robot = new Robot( );
} catch (AWTException awte) {
System.err.println ("Can't get a Robot");
awte.printStackTrace( );
}
}
public void paint (Graphics g) {
if ((robot == null) || (point.x == -1))
{
g.setColor (Color.blue);
g.fillRect (0, 0, mySize.width, mySize.height);
return;
}
Rectangle grabRect ...