Animate Transitions Between Tabs #8
Chapter 1, Basic JComponents
|
35
HACK
Once the transition finishes, the animation step is set back to -1, the previ-
ous tab is stored, and the screen is repainted one last time, without the tran-
sition effects.
Drawing the Animation
The TransitionTabbedPane is now set up with the proper resources and
repaints, but it still isn’t drawing the animation. Because the animation is
going to partially or completely obscure the tabs underneath, the best place
to draw is right after the children are painted:
public void paintChildren(Graphics g) {
super.paintChildren(g);
if(step != -1) {
Rectangle size = this.getComponentAt(0).getBounds( );
Graphics2D g2 = (Graphics2D)g;
paintTransition(g2, step, size, buf);
}
}
public void paintTransition(Graphics2D g2, int step,
Rectangle size, Image prev) {
}
This code puts all of the custom drawing into the paintTransition( )
method, currently empty. It will only be called if step isn’t -1, meaning dur-
ing a transition animation. The
paintTransition( ) method provides the
drawing canvas, the current animation step, the size and position of the con-
tent area (excluding the tabs themselves), and the image buffer that stores
the previous tab’s content. By putting all of this in a single method, sub-
classes can build their own animations very easily. Example 1-17 is a simple
transition with a white rectangle that grows out of the center, filling the
screen, then shrinking again to reveal the new tab content.
Example 1-17. Setting up an animated transition
public class InOutPane extends TransitionTabbedPane {
public void paintTransition(Graphics2D g2, int state,
Rectangle size, Image prev) {
int length = getAnimationLength( );
int half = length/2;
double scale = size.getHeight( )/length;
int offset = 0;
// calculate the fade out part
if(state >= 0 && state < half) {

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.