How do I fade an image in swing?

blank picture blank · Feb 9, 2010 · Viewed 19.1k times · Source

I've got class which inherits from JPanel with an image on it and i want to set up a little animation to display the panel/image and then fade it out when an event fires.

I presumably set up a thread and fire off the animation but how do I do actually do the fade?

Answer

Ash picture Ash · Feb 9, 2010

You can do the threading yourself, but it might be easier to use the Trident library to handle it. If you create a setter on your class called (say, setOpacity), you can ask trident to interpolate the "opacity" field from 1.0 to 0.0 over a specific period of time (here's some of the docs on how to use Trident).

When you're painting the image, you can do the transparency with an AlphaComposite, using the updated "opacity" value for the composite's alpha parameter. There is a Sun tutorial that includes an alpha composite example.