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

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.