O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

287
Chapter 8
C H A P T E R E I G H T
Rendering
Hacks 56–64
Sometimes it’s not what you put into your GUI, but how you draw it. The
hacks in this chapter are based in some way on using (or abusing) how
AWT and Swing render the graphic contents of a GUI. In several cases, we
use Java2D to bring graphic transformations and color-handling to Swing
components. In others, we use AWT’s font handling to change compo-
nents; not just
JTextComponents, but any components that need to draw text
to render themselves. And in still other cases, we mess with the process by
which Swing renders its contents.
H A C K
#56
Create a Magnifying Glass Component Hack #56
Zoom in on those pixels with a little creative abuse of the AWT’s debugging-
oriented
Robot class.
Some graphics programs use a component that shows a magnified view of
what the cursor is currently hovering over. This can be very helpful for doing
pixel-accurate editing of a picture.
It should be simple enough to do in Swing—get pixels from one component
and put them in another—but there are some missing pieces. Specifically,
how do you get the pixels out of the source component as an
Image so you
can
drawImage( ) them into the magnified component? You could do this if
you owned the source component and set it up with a double-buffer because
creating the offscreen buffer would require creating an
Image, which is
exactly what you needed anyway. But for an arbitrary
JComponent, you can’t
assume that level of access to the source’s pixels.
But there’s another option back in AWT: the
Robot class, introduced in J2SE
1.3. It has a
createScreenCapture( ) method that can grab the screen, or just
part of it, and return it as a Java2D
BufferedImage. This is what we need to
get things going.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required