
300
|
Chapter 8, Rendering
#59 Create a Color Eyedropper
HACK
H A C K
#59
Create a Color Eyedropper
Hack #59
Enhance your color pickers with an eyedropper tool that grabs a color from
anywhere on the screen.
Most paint tools give you an eyedropper, but I’ve never seen a Java program
do it. Getting a screen pixel requires native access, which is usually blocked
off from Java programs. Java 1.3 introduced a new method to the
Robot
class, getPixelColor( ), which can retrieve the color anywhere on the screen.
The problem is that you don’t get mouse events once the cursor leaves your
JFrame. This is fine if you only want to select colors from your own applica-
tion, but a color chooser needs to select from anywhere on the screen. Java
5.0 introduces new APIs for getting complete mouse events, but that doesn’t
help us today.
The answer to this tricky problem, of course, is to cheat! This hack makes a
screenshot and then paints it into a
JFrame called ColorChooserDemo, which
fills the entire screen. The screenshot is indistinguishable from the real desk-
top except that nothing in the background updates. However, since the
screenshot is only needed while the user selects a color, this should be OK.
ColorChooserDemo also has a JLabel in the center of the screen, which dis-
plays the currently selected color. Once the user has finished selecting a
color by releasing the mouse, the entire frame will disappear and the ...