Alpha Icons
Posted by Darryl Burke on August 22, 2010
These Alpha Icons wrap any Icon and paint it with the specified transparency. As Swing does not play well with an Icon that is not itself an ImageIcon but requires to show an animated GIF, two implementations are provided: AlphaIcon, which is good for wrapping any Icon, including an ImageIcon with a static image, and AlphaImageIcon which extends ImageIcon and can provide transparency for an ImageIcon that holds an animated image.
Each implementation provides a constructor that takes two parameters: the icon to be wrapped, and the opacity, a float value in the range 0.0F (fully transparent) to 1.0F (fully opaque).
When combined with Rob’s CompoundIcon with a Z_AXIS alignment, AlphaIcon and AlphaImageIcon allow you to overlay one Icon on another with the bottom Icon showing through. Multisort Table Header Cell Renderer showcases the use of AlphaIcons with varying transparency to indicate multiple sort orders in the header of a JTable.
Get The Code
AlphaIcon.java
AlphaImageIcon.java
See Also
Compound Icon
Multisort Table Header Cell Renderer
Related Reading
Java API: javax.swing.Icon
Java API: java.awt.AlphaComposite
Andres Almiray said
Hi Darryl, it looks like both links point to DualIcon.java instead ;-)
Darryl Burke said
I’ve updated the links, thanks for pointing out the error.
Darryl
Moiz Bhukhiya said
Can these classes be used for commercial purpose? Thanks!
Darryl Burke said
Like all code published on the blog, these classes are free to use, at your own risk . A link to the blog page in the doc comments or elsewhere would be nice, but is by no means mandatory.
Darryl
lorenzop said
thank you for your hard work. I only just came across your classes, plenty I’ve found useful and plenty to learn from you.
Derli said
Thanks!! it works Greats Darryl !
Added the following lines to animate a Fade in my App:
private Component parent;
public void setAlpha(float newAlpha)
{
alpha = newAlpha;
parent.repaint();
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
if (icon instanceof ImageIcon) {
image = ((ImageIcon) icon).getImage();
} else {
image = null;
}
this.parent = c; // <– Added!
g2 = (Graphics2D) g.create();
g2.setComposite(AlphaComposite.SrcAtop.derive(alpha));
icon.paintIcon(c, g2, x, y);
// g2.dispose();
}