32
|
Chapter 1, Basic JComponents
#8 Animate Transitions Between Tabs
HACK
The last line of the main( ) method starts a new thread to manage the back-
ground image.
Because the code is completely encapsulated in the
BackgroundLoader class, you could add space images to a
component that uses a scroll pane, not just a
JTextArea.
H A C K
#8
Animate Transitions Between Tabs Hack #8
This hack shows how to create animated transitions that play whenever the
user switches tabs on a
JTabbedPane.
One of Swing’s great strengths is that you can hack into virtually anything.
In particular, I love making changes to a component’s painting code. The
ability to do this is one of the reasons I prefer Swing over SWT. Swing gives
me the freedom to create completely new UI concepts, such as transitions.
With the standard paint methods, Swing provides most of what you will
need to build the transitions. You will have to put together three additional
things, however. First, you need to find out when the user actually clicked
on a tab to start a transition. Next, you need a thread to control the anima-
tion. Finally, since some animations might fade between the old and new
tabs, you need a way to provide images of both tabs at the same time. With
those three things, you can build any animation you desire.
Building a Basic Tabbed Pane
To keep things tidy, I have implemented this hack as a subclass of
JTabbedPane, except for the actual animation drawing, which will be dele-
gated to a further subclass. By putting all of the heavy lifting into the parent
class, you will be able to create new animations easily.
Example 1-16 is the basic skeleton of the parent class.
frame.pack( );
frame.show( );
new Thread(new BackgroundLoader(viewport)).start( );
}
Example 1-16. A skeleton for the transition manager
public class TransitionTabbedPane extends JTabbedPane
implements ChangeListener, Runnable {
protected int animation_length = 20;
Example 1-15. Testing the space image background (continued)

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.