Sleepless Nights – 10 Types of People
![]()
Project Granite aims to provide blueprints for adding animation to SWT applications using the Trident animation engine. Granite is an SWT RIA that connects to Amazon E-commerce backend and shows a list of albums for a specific performer. It is a pure SWT application with three dependencies ā Trident, classes generated by the wsimport tool from the Amazon E-commerce WSDL and Eclipse Jobs library for performing networking tasks on background threads.
Over the next few entries iām going to show code snippets that illustrate how Trident can be used to add simple and complex animations to your SWT applications. The full code is in the SVN repository, and here are two videos that show the different parts of Granite in action.
Asynchronously connecting to Amazon to fetch and display the list of albums, with fading and looping load progress animation, smooth album scrolling, showing bigger album art / track listing in a separate window and switching between different albums:
Looping scrolling of the album track listing, pausing at the end of each cycle to allow easier reading:
Timeline scenarios in the Trident animation library allow combining multiple timeline scenario actors in a parallel, sequential or custom order. Out of the box, Trident supports timelines, extensions of Runnable class and extensions of SwingWorker class, but the applications can easily create a custom implementation of the TimelineScenarioActor interface.
SwingWorker is an indispensable tool in the arsenal of a Swing programmer, and allows separating the long-running tasks that run on background threads from updating the UI components that must happen on the Event Dispatch Thread. While SWT does not have a direct counterpart, Eclipse core libraries have a very similar concept in Eclipse Jobs. And while the full functionality of Eclipse Jobs allows arbitrary dependencies and fine grained scheduling of interrelated jobs, you can wrap an Eclipse Job as a custom Trident timeline scenario actor and use the TimelineScenario APIs to seamlessly integrate an Eclipse Job in your Trident-powered SWT application.
Here is the complete source code to do this:
import org.eclipse.core.runtime.jobs.*;
import org.pushingpixels.trident.TimelineScenario.TimelineScenarioActor;
public abstract class EclipseJobTimelineScenarioActor extends Job implements
TimelineScenarioActor {
volatile transient boolean isDone = false;
public EclipseJobTimelineScenarioActor(String name) {
super(name);
this.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
isDone = true;
}
});
}
@Override
public boolean isDone() {
return isDone && (this.getState() == Job.NONE);
}
@Override
public void play() {
this.schedule();
}
@Override
public void resetDoneFlag() {
throw new UnsupportedOperationException();
}
@Override
public boolean supportsReplay() {
return false;
}
}
The play() method calls Job.schedule(), scheduling it for immediate execution. The isDone() method is called internally by the Trident engine on every pulse. The implementation registers a JobChangeListener to track the state of the job, and returns the relevant boolean value. Just as with SwingWorkers, the supportsReplay() returns false, and resetDoneFlag() throws an exception.
The timeline scenario below has the following steps which run in a sequential fashion:
The first step is done using our EclipseJobTimelineScenarioActor (which would be done with a TimelineSwingWorker in a Swing application):
private TimelineScenario getLoadImageScenario(final Item albumItem) {
TimelineScenario loadScenario = new TimelineScenario.Sequence();
// load the image
EclipseJobTimelineScenarioActor imageLoadWorker = new EclipseJobTimelineScenarioActor(
"Load image") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
URL url = new URL(albumItem.getMediumImage().getURL());
image = new Image(Display.getDefault(), url.openStream());
return Status.OK_STATUS;
} catch (Throwable t) {
t.printStackTrace();
return Status.CANCEL_STATUS;
}
}
};
loadScenario.addScenarioActor(imageLoadWorker);
// scale if necessary
TimelineRunnable scaler = new TimelineRunnable() {
@Override
public void run() {
if (image != null) {
float vFactor = (float) OVERVIEW_IMAGE_DIM
/ (float) image.getImageData().height;
float hFactor = (float) OVERVIEW_IMAGE_DIM
/ (float) image.getImageData().width;
float factor = Math.min(1.0f, Math.min(vFactor, hFactor));
if (factor < 1.0f) {
// scaled to fit available area
image = GraniteUtils.getScaledInstance(image,
(int) (factor * image.getImageData().width),
(int) (factor * image.getImageData().height));
}
imageLoadedDone = true;
}
}
};
loadScenario.addScenarioActor(scaler);
// and fade it in
Timeline imageFadeInTimeline = new Timeline(AlbumOverviewComponent.this);
imageFadeInTimeline.addPropertyToInterpolate("imageAlpha", 0.0f, 1.0f);
imageFadeInTimeline.addCallback(new SWTRepaintCallback(
AlbumOverviewComponent.this));
imageFadeInTimeline.setDuration(500);
loadScenario.addScenarioActor(imageFadeInTimeline);
return loadScenario;
}
You will need the following Eclipse libraries in your classpath:
As you can see, it is quite easy to extend the existing functionality of Trident scenarios by wrapping external modules as custom timeline scenario actors.
Trident animation library allows adding a short fade-out sequence to a Swing / SWT window that is being closed. This can provide an unobtrusive visual feedback to the user, confirming his action and smoothly guiding his eye to the new application state.
Here is a utility method to add a fade-out sequence to disposing a Swing window – this code requires the latest builds of JDK7 that added the Window.setAlpha(float) method:
public static void fadeOutAndDispose(final Window window,
int fadeOutDuration) {
Timeline dispose = new Timeline(window);
dispose.addPropertyToInterpolate("opacity", 1.0f, 0.0f);
dispose.addCallback(new UIThreadTimelineCallbackAdapter() {
@Override
public void onTimelineStateChanged(TimelineState oldState,
TimelineState newState, float durationFraction,
float timelinePosition) {
if (newState == TimelineState.DONE) {
window.dispose();
}
}
});
dispose.setDuration(fadeOutDuration);
dispose.play();
}
and the matching method for disposing an SWT shell with a fade-out sequence, which requires SWT 3.4 to run:
public static void fadeOutAndDispose(final Shell shell, int fadeOutDuration) {
Timeline dispose = new Timeline(shell);
dispose.addPropertyToInterpolate("alpha", 255, 0);
dispose.addCallback(new UIThreadTimelineCallbackAdapter() {
@Override
public void onTimelineStateChanged(TimelineState oldState,
TimelineState newState, float durationFraction,
float timelinePosition) {
if (newState == TimelineState.DONE) {
shell.dispose();
}
}
});
dispose.setDuration(fadeOutDuration);
dispose.play();
}
Instead of calling Shell.dispose() or Window.dispose(), call the fadeOutAndDispose() method, passing the duration of the fade-out sequence in milliseconds. A previous entry has discussed another option – overriding the Window.dispose() method in your custom Swing class. While this works in Swing, SWT does not allow extending the Shell class outside the org.eclipse.swt.widgets package.