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

222
|
Chapter 6, Transparent and Animated Windows
#42 Make Your Frame Dissolve
HACK
Do the Drawing
Now that the component will be repainted for each frame of the animation,
you can finally do some drawing. Fading to nothing is really easy with
Swing. You just need to draw the background image first, and then draw the
frame on top using a
Composite
. A
Composite
is a class that knows to adjust
the standard mechanism in some way. An
AlphaComposite
will draw par-
tially transparent images depending on the alpha value you pass in. An alpha
value of
1 will draw the image fully opaque, while a value of 0 will be com-
pletely transparent. Values between
1 and 0 will draw the image partially
transparent. Always be sure to save the old composite so you can return the
Graphics
object to its original state when you are done:
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
// draw the screen, offset in case the window isn't at 0,0
g.drawImage(screen_buffer,-fullscreen.getX( ),
-fullscreen.getY( ),null);
// draw the frame
Composite old_comp = g2.getComposite( );
Composite fade = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER,1.0f-((float)count)/20f);
g2.setComposite(fade);
g2.drawImage(frame_buffer,frame.getX(),frame.getY( ),null);
g2.setComposite(old_comp);
}
The class in Example 6-2 creates a frame with one button called quit. When
you press the Quit button, the dissolve will be activated, fading the window
into nothing and then calling
System.exit( ). If you compile and run the
code, it will look something like Figure 6-4.
Figure 6-4. A fade dissolve

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