LISTING 7
Figure 4
Figure 5
crazy with JLayer by building a magnifying glass that will magnify whatever is
underneath the mouse as the mouse
moves, as shown in Figure 6.
The code shown in Listing 7 is roughly
the same as before. The difference is
that this time it scales the graphics
before drawing into an image. Then it
draws the image back to the screen with
a nice round clip.
Drawing components into a temporary image is a really useful technique
because there are so many ways to post-process an image. To further extend the
magnifying glass, you could add a distortion filter to give the scaled image a
rounded effect.
@Override
public void paint(Graphics g, JComponent c) {
//draw regular
super.paint(g,c);
//draw into buffer
Graphics2D g2 = img.createGraphics();
int ih = img.getHeight();
int iw = img.get Width();
//fill with white
g2.setPaint(Color.WHITE);
g2.fillRect(0, 0, img.get Width(), img.getHeight());
//render view component scaled and translated
Graphics2D g3 = (Graphics2D) g2.create();
g3.translate(-pt.x + iw, -pt.y + ih* 2);
g3.scale( 2, 2);
g3.translate(-pt.x/2 - iw/4, -pt.y/2 - ih/4);
super.paint(g3,c);
g3.dispose();
//draw black border
g2.setPaint(Color.BLACK);
g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.
VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke( 3));
g2.draw(new Ellipse2D.Double(0,0,iw,ih));
g2.drawRect(0,0, iw- 1, ih- 1);
g2.dispose();
//draw image to screen
Shape oldClip = g.getClip();
int mx = pt.x-img.get Width()/2;
int my = pt.y-img.getHeight();
g.setClip(new Ellipse2D.Double(mx,my,iw,ih));
g.drawImage(img, mx, my, null);
g.setClip(oldClip);
}
COMMUNITY
JAVA IN ACTION
Conclusion
JLayer is a very powerful addition to
Swing that makes many previously hard
or impossible effects easy to do in a
clean and supported way. JLayer proves
that Swing still has a lot of life left in
it, and Java SE 7 provides new ways
of extending Swing to do interesting
things. (And being more generified is
always nice, too.)
The examples shown here are just the
tip of the iceberg. You could use JLayer to
implement status overlays, busy indicators, global right-click menus, and
much more. </article>
ABOUT US
Figure 6
that final image to the screen. Figure 4
shows an example of a button that can
be blurred, and Figure 5 shows a
blurred button.
Because the JLayer repaints any time
its view control changes, we don’t need
to track any state. A toggle button can
simply toggle the enabled property of the
button, and Swing takes care of the rest.
As a final example, Listing 7 shows
how you can do something completely
LEARN MORE
To learn more about JLayer, read the Java
docs for JLayer and LayerUI:
•;JLayer
•;LayerUI
blog