
Animate Transitions Between Tabs #8
Chapter 1, Basic JComponents
|
33
HACK
TransitionTabbedPane extends the standard JTabbedPane and also imple-
ments
ChangeListener and Runnable. ChangeListener allows you to learn
when the user has switched between tabs. Since the event is propagated
before the new tab is painted, inserting the animation is very easy.
Runnable
is used for the animation thread itself.
You could have split the thread into a separate class, but I
think that keeping all of the code together makes the system
more encapsulated and easier to maintain.
TransitionTabbedPane adds one new property, the animation length. This
defines the number of steps used for the transition, and it can be set by the
subclass or external code.
Scheduling the Animation
Since the pane was added as a ChangeListener to itself, the stateChanged( )
method will be called whenever the user switches tabs. This is the best place
to start the animation thread. Once started, the thread will capture the pre-
vious tab into a buffer, loop through the animation, and control the repaint
speed:
// threading code
public void stateChanged(ChangeEvent evt) {
new Thread(this).start( );
}
protected int step;
protected BufferedImage buf = null;
protected int previous_tab = -1;
public void run( ) {
step = 0;
public TransitionTabbedPane( ) {
super( );
this.addChangeListener(this);
}
public int getAnimationLength( ) {
return this.animation_length; ...