Close your Swing / SWT windows in style

August 2nd, 2009  |  Swing · SWT / Eclipse · Trident

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.